In jquery validation for textbox as numeric - javascript

To make user ID validation for only numeric values ! here is my code please suggest me where am making wrong in my code
function login() {
UserID = $('#txtLoginScreen_UserId').val();
password = $('#txtLoginScreen_MPIN').val();
if (UserID.length == 0) {
alert("Please enter User ID");
} else if (password.length == 0) {
alert("Please enter MPIN");
}
/* Here am unable to make USer ID validation for restricting only numeric values upto 12 */
/* else if (isNaN(parseInt($("#txtLoginScreen_UserId").val()))) {
alert('It must be numbers');
return false;
}*/
/* Validate for UserID */
/* $("#txtLoginScreen_UserId").keypress(function(e) {
alert("validate");
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
//display error message
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false;
}
});
*/
else {
}

if()$.isNumeric(UserID){
} else{
alert("not numaric");
}

Try this,
if (parseInt(UserID) > 0) {
alert("Please enter alphanumeric characters only");
}

Related

I am trying to validate mobile with javaScript but it not working

I have a mobile and I want to check if the mobile number is less then 10 or greater then 13 then I want to show the message
My code:
<input name="mobile" id="mobile" placeholder="+91" class="form-control tboxs" type="text" style="font-family: 'JameelKhushkhatLRegular'">
<button style="width: 100%" type="button" id="submit" value="submit" class="btn-theme-colored btn">SUBMIT <span class="glyphicon glyphicon-send">
<script>
$('#submit').click(function(){
if($('#first_name').val() == '' ){
alert('Name can not be left blank and atleast 4 char long');
return false;
}else if(!$("input[name='redio_gender']:checked").val()){
alert('Please Select Gender');
return false;
}else if($('#multiple').val( ) == '') {
alert('Please Select Age');
return false;
}else if($('#profession').val( ) == '') {
alert('Please Select your Profession');
return false;
}else if($('#taluka').val( ) == '') {
alert('Please Select Taluka');
return false;
}else if($('#village').val( ) == '') {
alert('Please Enter village');
return false;
}else if($('#interest').val( ) == '') {
alert('Please Select Area of Interest');
return false;
}else if($('#masjid').val( ) == '') {
alert('Please Enter Nearest Masjid');
return false;
}else if($('#mobile').val( ) == '' || parseInt($('#mobile').val() < 10 ) || parseInt($('#mobile').val() > 13)) {
alert('Please Enter Valid Mobile Number');
return false;
}else{
$.ajax({
--
--
});
}
});
</script>
In the above code, I validate my code with javascript.
Try this :
var mob = '03311111111';
if( mob.length < 10 || mob.length > 13){
// show error message
}
https://jqueryvalidation.org
$.validator.addMethod(
'phone',
function (value, element, requiredValue) {
var phoneRegexp = /^\+380\d{7,10}$/;
return phoneRegexp.test(value);
},
);
var validator = $('#form_id').validate({
debug: true,
errorClass: 'error-class',
errorElement: 'div',
rules: {
'phone': {
required: true,
phone: true,
minlength: 10,
maxlength: 13
}
},
}
);
You can try the following:
$('#submit').click(function(){
var mobile = $('#mobile').val();
if(mobile.length < 10 || mobile.length > 13) {
//mobile length is less than 10 or greater than 13, show error message
}
});
Your final code would be this:
<script>
$('#submit').click(function(){
var mobile = $('#mobile').val();
if($('#first_name').val() == '' ){
alert('Name can not be left blank and at least 4 char long');
return false;
} else if(!$("input[name='redio_gender']:checked").val()){
alert('Please Select Gender');
return false;
} else if($('#multiple').val( ) == '') {
alert('Please Select Age');
return false;
} else if($('#profession').val( ) == '') {
alert('Please Select your Profession');
return false;
} else if($('#taluka').val( ) == '') {
alert('Please Select Taluka');
return false;
} else if($('#village').val( ) == '') {
alert('Please Enter village');
return false;
} else if($('#interest').val( ) == '') {
alert('Please Select Area of Interest');
return false;
} else if($('#masjid').val( ) == '') {
alert('Please Enter Nearest Masjid');
return false;
} else if(mobile.length < 10 || mobile.length > 13) {
alert('Please Enter Valid Mobile Number');
return false;
} else {
$.ajax({
--
--
});
}
});
</script>
Or you could use html attributes to do that by using minlength and maxlength on the text input and you may even want to switch the input type from text to tel
<input name="mobile" id="mobile" placeholder="+91" class="form-control tboxs" type="tel" style="font-family: 'JameelKhushkhatLRegular'" minlength='10' maxlength='13'>

Force input pattern with only letter [duplicate]

This question already has answers here:
How do I make an input field accept only letters in javaScript?
(5 answers)
Closed 6 years ago.
I need a function that forces an input type with only letter, number is not allowed. I still have this function and i want to add this new function. Can you please help me?
<script>
function valida() {
if ($('#cut').val() == '') {
alert("u must insert something");
$('#cut').addClass("ui-state-error");
return false;
}
if ($('#tas').val() == '') {
alert(u must insert something");
$('#tas').addClass("ui-state-error");
return false;
}
if ($('#nom').val() == '') {
alert("u must insert something");
$('#nom').addClass("ui-state-error");
return false;
}
}
</script>
Try below code. checkAlphabets() will check either entered value is alfabates or not
<script>
function checkAlphabets(e) {
try {
if (window.event) {
var charCode = window.event.keyCode;
}
else if (e) {
var charCode = e.which;
} else {
return true;
}
if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123))
return true;
else
return false;
}
catch (err) {
alert(err.Description);
}
}
function validate() {
if ($('#cut').val() == '') {
alert("u must insert something");
$('#cut').addClass("ui-state-error");
return false;
}
if ($('#tas').val() == '') {
alert(u must insert something");
$('#tas').addClass("ui-state-error");
return false;
}
if ($('#nom').val() == '') {
alert("u must insert something");
$('#nom').addClass("ui-state-error");
return false;
}
if (checkAlphabets($('#nom').val()) == false) {
alert("u must insert something");
$('#nom').addClass("ui-state-error");
return false;
}
}
</script>
Ref: Link

JavaScript - If Else

I have JavaScript code for some function with If Else statements. But it is too long. I need to make it easy. So the problem is, how to reduce the line of codes in the following function?
function clickFunction(e) {
if(document.getElementsByName('insert_data1')[0].value == 1 || document.getElementsByName('insert_data1')[0].value == 0){
document.getElementsByName('inputvalue1')[0].innerHTML = document.getElementsByName('insert_data1')[0].value;
}
else{
alert("Please enter 0 or 1 !!");
}
if(document.getElementsByName('insert_data2')[0].value == 1 || document.getElementsByName('insert_data2')[0].value == 0){
document.getElementsByName('inputvalue2')[0].innerHTML = document.getElementsByName('insert_data2')[0].value;
}
else{
alert("Please enter 0 or 1 !!");
}
if(document.getElementsByName('insert_data3')[0].value == 1 || document.getElementsByName('insert_data3')[0].value == 0){
document.getElementsByName('inputvalue3')[0].innerHTML = document.getElementsByName('insert_data3')[0].value;
}
else{
alert("Please enter 0 or 1 !!");
}
if(document.getElementsByName('insert_data4')[0].value == 1 || document.getElementsByName('insert_data4')[0].value == 0){
document.getElementsByName('inputvalue4')[0].innerHTML = document.getElementsByName('insert_data4')[0].value;
}
else{
alert("Please enter 0 or 1 !!");
}
e.preventDefault();
return false;
}
This is not tested at all but perhaps something like this might do the trick?
function clickFunction(e) {
e.preventDefault();
var inputs=['inputvalue1','inputvalue2','inputvalue3','inputvalue4'];
var fields=['insert_data1','insert_data2','insert_data3','insert_data4'];
fields.forEach( function(e,i,a){
var field=document.getElementsByName( e )[0];
if( field.value==1 || field.value==0 ) document.getElementsByName( inputs[i] )[0].innerHTML=field.value;
else alert("Please enter 0 or 1 !!");
});
return false;
}

Jquery form validation coding

My Jquery validation is not working, below is the script coding. I am getting a
Fatal error: Uncaught exception
error and not sure why. I know one of the reasons can be the validation code isnt correct. Is the coding correct or is there errors?
<script type="text/javascript">
$('form#contact').submit(function(e) {
var isValidZip = /(^\d{5}$)|(^\d{5}-\d{4}$)/.test(jQuery('#form_zip').val());
var isValidYear = /^\d{4}$/.test(jQuery('#gradDate').val());
var year_number = parseInt(jQuery('#gradDate').val());
var isValidEmail = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(jQuery('#form_email').val());
var first_name = jQuery.trim(jQuery('#first_name').val());
var last_name = jQuery.trim(jQuery('#last_name').val());
var form_email = jQuery.trim(jQuery('#form_email').val());
var street = jQuery.trim(jQuery('#street').val());
var city = jQuery.trim(jQuery('#city').val());
var state = jQuery.trim(jQuery('#state').val());
var isValidPhone = /^[2-9]\d{2}[2-9]\d{2}\d{4}$/.test(jQuery('#phone_day').val());
function validZip(zip)
{
if (zip.match(/^[0-9]{5}$/)) {
return true;
}
zip=zip.toUpperCase();
if (zip.match(/^[A-Z][0-9][A-Z][0-9][A-Z][0-9]$/)) {
return true;
}
if (zip.match(/^[A-Z][0-9][A-Z].[0-9][A-Z][0-9]$/)) {
return true;
}
return false;
}
if(!validZip(jQuery('#form_zip').val())){
alert('Please enter a valid Zip Code.');
}
else if(!isValidYear || (year_number > <?php echo date('Y')?>)){
alert('Please enter a valid High School Graduation Year.');
}
else if(!isValidEmail (jQuery('#form_email').val())){
alert('Please enter a valid Email Address.');
}
else if(first_name.length <= 0 || first_name == 'First Name' || (!first_name.match(/[a-zA-Z]/)) || (first_name.match(/[0-9]/))){
alert('Please enter your First Name.');
}
else if(last_name.length <= 0 || last_name == 'Last Name' || (!last_name.match(/[a-zA-Z]/)) || (last_name.match(/[0-9]/))){
alert('Please enter your Last Name.');
}
else if(street.length <= 0 || street == 'Street Address'){
alert('Please enter your Street Address.');
}
else if(city.length <= 0 || city == 'City'){
alert('Please enter your City.');
}
else if(state.length <= 0 || state == 'State'){
alert('Please enter your State by 2 letter abbreviation.');
}
else if(country.length <= 0 || country == 'Other'){
alert('Please enter your Country.');
}
else if(!isValidPhone){
alert('If your phone number is correct, close this box and then Click the button in the form.');
}
else {
$('form#mainform').submit();
}
return false;
}
return false;
}
});
</script>
You have php inside your JavaScript code:
else if(!isValidYear || (year_number > <?php echo date('Y')?>)){

Getting Jquery code to stay after form has finished submitting

My code Jquery code adds text to a table when a user makes a mistake in their form. However the text dissapears once it has finished checking and thus only appears for a brief split second.
Here is the Username validator:
function validateUserName()
{
var u = document.forms["NewUser"]["user"].value
var uLength = u.length;
var illegalChars = /\W/; // allow letters, numbers, and underscores
if (u == null || u == "")
{
$("#ErrorUser").text("You Left the Username field Emptyyy");
return false;
}
else if (uLength <4 || uLength > 11)
{
$("#ErrorUser").text("The Username must be between 4 and 11 characters");
return false;
}
else if (illegalChars.test(u))
{
$("#ErrorUser").text("The Username contains illegal charectors men!");
return false;
}
else
{
return true;
}
}
To prevent the form submission, you need to prevent the default action. Give this way:
function validateUserName(e)
{
e.preventDefault();
var u = document.forms["NewUser"]["user"].value;
var uLength = u.length;
var illegalChars = /\W/; // allow letters, numbers, and underscores
if (u == null || u == "")
{
$("#ErrorUser").text("You Left the Username field Emptyyy");
return false;
}
else if (uLength <4 || uLength > 11)
{
$("#ErrorUser").text("The Username must be between 4 and 11 characters");
return false;
}
else if (illegalChars.test(u))
{
$("#ErrorUser").text("The Username contains illegal charectors men!");
return false;
}
else
{
return true;
}
}
And you need to call the event this way:
$("form").onsubmit(validateUserName);
Update: Based on the comment.
Change your <form> tag markup this way:
<form name="NewUser" id="myform">
And in the JavaScript, use this way:
$("form").onsubmit(function(e){
e.preventDefault();
var u = document.forms["NewUser"]["user"].value;
var uLength = u.length;
var illegalChars = /\W/; // allow letters, numbers, and underscores
if (u == null || u == "")
{
$("#ErrorUser").text("You Left the Username field Emptyyy");
return false;
}
else if (uLength <4 || uLength > 11)
{
$("#ErrorUser").text("The Username must be between 4 and 11 characters");
return false;
}
else if (illegalChars.test(u))
{
$("#ErrorUser").text("The Username contains illegal charectors men!");
return false;
}
else
{
return true;
}
});
As already mentioned in the comment by #adeneo, you need to prevent your form from submitting.
<input type="submit" value="Submit" onclick="if(!validateUserName()) return false;"/>
This will prevent your form from submitting data if the form has errors. You already return true/false from your Javascript function, just utilizing those.

Categories

Resources