Form Validation With jQuery
Well, i have a problem validating a form with jQuery. I'm Not using any validation Framework (Such as http://docs.jquery.com/Plugins/Validation), because i need to do this without any Pre-Builded Solution (It's an user requirement, Strange, by the way). I Have a Textbox, And I Need to Validate Any String, but, that string has no numbers or Special Characters (Such as !"·$%&/()=;,:.-_), It's a Person Name. This is My Code:
<script type="text/javascript">
$(document).ready(function(){
var onlyChars = /^[A-Za-z]+$/;
var onlyNums = /^[0-9]+$/;
var mail = /^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[@][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/;
var name = $("#txtname");
function validateName()
{
if (name.val().length > 25)
{
alert("Too Longer");
return false;
}
else if (name.val().match(/^[A-Za-z]+$/))
{
alert("Error, Pattern Doesn't Match");
return false;
}
else
开发者_C百科 {
return true;
}
}
$("#submitform").submit(function(){
if (validateName())
{
return true;
}
else
{
return false;
}
});
});
</script>
The First Validation It's Ok (If I Write More Than 25 Characters, The Alert is triggered and the submit event is aborted), But, the second validation doesn't do it. In This case happens two events:
The Field, having Not-Allowed Characters "Pass" the validation and the form is submitted.
The Field, having only the allowed Characters Don't Pass the validation and the form isn't submitted.
I've Checked everything, and the "Two Issues" are completely Random.
Can You give me some Help?
Thanks a Lot!
PS: Sorry for the English, I'm not a "Native-Speaker"
Your code is saying ==>
If name matches correctly, say "pattern doesn't match"
Have a look at your code here:
else if (name.val().match(/^[A-Za-z]+$/))
//change this to else if (!(name.val().match(/^[A-Za-z]+$/)))
{
alert("Error, Pattern Doesn't Match");
return false;
}
else
{
return true;
}
Okay, I'll bite.
Look closely at this code:
else if (name.val().match(/^[A-Za-z]+$/))
{
alert("Error, Pattern Doesn't Match");
return false;
}
That reads: If name matches the pattern tell the user it doesn't and don't submit. You want to inverse that:
else if (!name.val().match(/^[A-Za-z]+$/))
{
alert("Error, Pattern Doesn't Match");
return false;
}
You should use Firebug and set a break point to walk the code, it'll probably give you a hint why your going into the wrong block of code.
精彩评论