The following code can be used for validating name like fields.(Useful when dealing with html forms)
This code uses two built in functions
indexOf() - Returns the position of the first occurrence of a specified value in a string and return -1 if not found.
<script type="text/javascript">
function validate()
{
var not_needed = "!@#$%^&*()+=-[]\\\';,./{}|\":<>? 1234567890";
if(document.myform.name1.value =="")
{
alert("Invalid name");
return false;
}
for (var i = 0; i < document.myform.name1.value.length; i++)
{
if (not_needed.indexOf(document.myform.name1.value.charAt(i)) != -1)
{
alert ("Invalid name");
return false;
}
}
This code uses two built in functions
1)charAt()
2) indexOf()
charAt()- Returns the character at the specified index in a string.
Ex: charAt(5)--> character at 6th position(Starting with 0)
Bellow code has a variable not_needed. You can simply specify the unwanted character inside the double quotes.
<script type="text/javascript">
function validate()
{
var not_needed = "!@#$%^&*()+=-[]\\\';,./{}|\":<>? 1234567890";
if(document.myform.name1.value =="")
{
alert("Invalid name");
return false;
}
for (var i = 0; i < document.myform.name1.value.length; i++)
{
if (not_needed.indexOf(document.myform.name1.value.charAt(i)) != -1)
{
alert ("Invalid name");
return false;
}
}
}
</script>
Form
<form action="sample.php" name="myform" method="post" onsubmit="return validate()">
Name: <input type="TEXT" name="name1">
0 comments:
Post a Comment