Forum Moderators: open
I have a telephone number field where the validation previously only allowed numbers. Now I need to change this to also allow the plus (+) sign, but no other letters. How can I do this?
Here's the JavaScript validation which is included in the head:
field_id: {
required: function(){
return(!isEmpty("field_id"));
}
,digits: true
}
Another question: If I add a '+' sing to the form field value as the default, how does one fix it to the field, i.e a person filling the field in/out should not be able to delete the sign ?
I'm including the following Doctype:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
Thanks
The DOCTYPE has no relevance.
As for preventing users from deleting the '+' value... there's not really a good way to do that. You could use two input fields, making one of them readonly (the one with the '+' value). But if you need to have them in a single input field, you won't be able to guarantee that the user can't change the value... you could use JavaScript to try an prevent the user from deleting it, but then users with JavaScript disabled would still be able to delete it. The best option would be to include some server side check when the form is submitted that makes sure the '+' is included even if the user has deleted it.
We use jQuery.
Here's a snippet of more of the code. It's incomplete and for example purposes only:
<script type="text/javascript">
$(document).ready(function() {
function isEmpty(item) {
var empty = true;
if ($("#"+item).val() != null) {
empty = ($("#"+item).val().length == 0);
}
return empty;
}
// validate contact form on keyup and submit
$("#contact_form").validate({
rules: {
field_id: {
required: function(){
return(!isEmpty("field_id"));
}
,digits: true
}
},
messages: {
field_id: {
required: "Please enter your contact number<br />"
,digits: "Your contact number must consist of only digits<br />"
,minlength: "Your contact number must consist of at least 10 numbers<br />"
,maxlength: "Your contact number must consist of no more than 10 numbers<br />"
}
}
});
});
</script>
I have only included the contact number field, where only digits are allowed. The telephone code is a separate form field.
I will most likely remove
min- and maxlength to allow people to add their telephone numbers as they want, as it's an international site, so difficult to know all the formats. The read-only suggestion will work, but won't be easy-on-the-eye. I'll play around with the JavaScript option and see how I get on. The site is heavily dependent upon JavaSript (that was a business decision), so in this case it's not a problem.
The function recognizes every valid NANP format that I've encountered so far and can be updated easily to add any new ones. Special characters can be ignored if you wish, and funny formats like "CALL-ME-2" work just as you'd expect.
The function is too long to post here. Sticky me if you'd like a copy.