Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Form validation of numeric characters in JavaScript

Tags:

javascript

I would like to perform form validation using JavaScript to check for input field only to contain numeric characters.So far, the validation checks for the field not being empty - which works fine.However, numeric characters validation is not working.I would be grateful for any help.Many thanks.

<script type="text/javascript">
//form validation
function validateForm()
{
var x=document.forms["cdp_form"]["univer_number"].value
if (x==null || x=="")
  {
  alert("University number (URN) field must be filled in");
  cdp_form.univer_number.focus();
  return false;
  }
else if (is_valid = /^[0-9]+$/.test(x))
    {
    alert("University number (URN) field must have numeric characters");
    cdp_form.univer_number.focus();
    return false;
  }
}
</script>


<input type ="text" id="univer_number" maxlength="7"    size="25"   name="univer_number" />
like image 747
Igor Novoselov Avatar asked Apr 01 '26 01:04

Igor Novoselov


1 Answers

Rather than using Regex, if it must only be numerals you can simply use IsNumeric in Javascript.

IsNumeric('1') => true; 
IsNumeric('145266') => true;
IsNumeric('abc5423856') => false;
like image 90
Mikecito Avatar answered Apr 03 '26 20:04

Mikecito