jQuery validation number - javascript

I have a single input field where the user can only enter a number between 2 AND 50. Anything above or below is invalid. It also MUST be a numeric value.
What I have so far is this:
$('#searchTimes').click(function() {
if($('#replyNumber').val()<=0) {
alert("Please select a value greater than 0 for number of guests");
$('#replyNumber').focus();
return;
}
if($('#replyNumber').val()>=51) {
alert("Please select a value less than or equal to 50 for number of guests");
$('#replyNumber').focus();
return;
}
if(isNaN($('#replyNumber').val())) {
alert("Please enter a numeric value only");
$('#replyNumber').focus();
return;
}
});
Is there a better more efficient way of writing that ^.
Also ... IF all of those IF statements are not true then I need to perform another function. How can I add that in?

_isValidNumber(number) {
var message;
var isValid;
switch(number){
case number >= 51:
message = "Please select a value less than or equal to 50 for number of guests";
isValid = false;
case number <= 0:
message = "Please select a value greater than 0 for number of guests";
isValid = false;
case isNumeric(number):
var message = "Please enter a numeric value only";
isValid = false;
default:
return true;
}
alert(message);
$('#replyNumber').focus()
return isValid;
}
function isNumeric(num){
return !isNaN(num)
}
var number = $('#replyNumber').val();
var numberIsValid = _isValidNumber(number);

I would try to abstract out duplicate code, like this:
<input id="replyNumber" >
<button id="searchTimes">click</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$('#searchTimes').click(function() {
var val = $('#replyNumber').val()
if(val<=0) showErr("Please select a value greater than 0 for number of guests");
else if(val>=51) showErr("Please select a value less than or equal to 50 for number of guests");
else if(isNaN(val))showErr("Please enter a numeric value only");
});
function showErr(msg){
alert(msg);
$('#replyNumber').focus();
}
</script>

This is what you need :D
$('#searchTimes').on('click',function() {
var do_function = 1;
if (!$.isNumeric($('#replyNumber').val())) {
alert("Please enter a numeric value only");
$('#replyNumber').focus().select();
} else if (+$('#replyNumber').val() < 2) {
alert("Please select a value at least 2 for number of guests");
$('#replyNumber').focus().select();
} else if (+$('#replyNumber').val() > 50) {
alert("Please select a value no more than 50 for number of guests");
$('#replyNumber').focus().select();
} else {
do_function = 0;
}
if (do_function) {
call_some_function();
}
});
Good luck!

Use HTML5 min and max attributes and an input of type number (which covers the numeric part you mentioned). Use rangeOverflow and rangeUnderflow Validity Properties to check your input and present the proper error (or custom error) messages.
Try the below snippet using the following values (null (empty input),1,55) and check the custom error messages created.
function validateInput() {
var txt = "";
if (document.getElementById("inp1").validity.rangeOverflow) {
txt = "Value larger than acceptable!";
}
if (document.getElementById("inp1").validity.rangeUnderflow) {
txt = "Value smaller than acceptable";
}
if (document.getElementById("inp1").validity.valueMissing) {
txt = "Please type a number!";
}
document.getElementById("output").innerHTML = txt;
}
document.getElementById("btn").addEventListener("click", function(){
validateInput();
});
<form>
<input type="number" id="inp1" name="numberInput" min="2" max="50" required>
<button id="btn">go</button>
</form>
<div id="output"></div>

Related

How to check if textbox value is not number?

<!DOCTYPE html>
<html>
<body>
<div id="text" class="CommentBox">
Some text :
<input type="text" />
</div>
<script>
$(document).ready(function () {
jQuery("#text").on("change", function () {
var x = $('#text').value;
if (isNaN(x))
{
window.alert("You have entered not a number");
return false;
});
});
});
</script>
</body>
</html>
I am trying to write javascript code to check if the given value is not number.If not i would like to give error message? If it is number I would like to check if it is integer and between 0 and 100.
Basically you need to convert to an Int before compare it with NaN which means something like:
var x = $('#text').value;
if ( isNaN( parseInt(x) ) ) {
// Not a decimal number.
}
There are a lot of syntax errors in your code.
Your selector checks your div for the change event instead of your input, which means it will never trigger the code.
You should use .val() to get the value of an element when using jQuery selectors instead of .value.
You can also use the this keyword inside the event handler to get the referenced element.
Besides that there were some misplaced ) and } in your code.
Below I have included an working sample of your code.
$(document).ready(function() {
jQuery("#text > input").on("change", function() {
var x = $(this).val();
if (isNaN(x)) {
window.alert("You have entered not a number");
return false;
} else if (x > 0 && x < 100) {
alert("number in between 0 and 100");
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="text" class="CommentBox">
Some text :
<input type="text" />
</div>
function numberOrNot(var input)
{
try
{
Integer.parseInt(input);
}
catch(NumberFormatException ex)
{
return false;
}
return true;
}
this will return true if your input is number, otherwise it will return false
try this code
you enter direct input on change or write id for input and pass it to javascript
$(document).ready(function() {
jQuery("input").on("change", function() {
var x = $('#text').val();
if (isNaN(x)) {
window.alert("You have entered not a number");
return false;
}
else{
if(x>=0 && x<=100)
{
window.alert("You have enter write number");
}else{
window.alert("You enter number between 0 to 100");
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="CommentBox">
Some text :
<input type="text" id="text" />
</div>
You can use try-catch and put as many conditions you want in try block Like this. I have put three conditions for now.
<script type="text/javascript">
function Validation(){
var number1=document.LoginForm.number1.value;
try{
if(number1==""){
throw "Empty";
}
if(isNaN(number1)){
throw "Not a Number";
}
if(number1<0 || number1>100){
throw "Out of range";
}
}
catch(err){
if (err=="Empty"){
alert("Number 1 and Number 2 fields cannot be empty");
}
if (err=="Not a Number"){
alert("Please enter a number");
}
if(err=="Out of Range"){
alert("Out of Range");
}
return false;
}
//return true;
}
</script>

Regex to allow only positive whole numbers and checking validity in jQuery

I have two input field like this in my HTML:
<input type="text" class="txtminFeedback" pattern="^\d+([\.\,][0]{2})?$" placeholder="Minimum Feedback">
<input type="text" class="txtmaxFeedback" pattern="^\d+([\.\,][0]{2})?$" placeholder="Maximum Feedback">
I've tried several regex patterns like following:
^\d+([\.\,][0]{2})?$
or
(^[0-9]+$|^$)
or
/^\d*$/
None of these worked whatsoever with the following code in jQuery:
if ($('.txtminFeedback').val() == "" && $('.txtmaxFeedback').val() == "") {
if ($('.txtmin')[0].checkValidity() && $('.txtmax')[0].checkValidity()) {
if ($('.txtSearch').val() == "") {
ShowMessage("Please enter the search term!");
return;
}
else {
PostAndUpdate($('.txtSearch').val(), $('input[name=type]:checked').val(), $('input[name=shipping]:checked').val(), $('input[name=condition]:checked').val(), $('.txtmin').val(), $('.txtmax').val(), $('.txtNegativeKeywords').val(), $('.txtminFeedback').val(), $('.txtmaxFeedback').val());
}
} else {
ShowMessage("You have entered incorrect value for minimum or maximum price!");
return;
}
} else if (!$('.txtminFeedback')[0].checkValidity() || !$('.txtmaxFeedback')[0].checkValidity())
{
ShowMessage("Please enter only positive value for minimum and maximum feedback.");
return;
}
User can leave the txtminfeedback and txtmaxfeedback empty if he wants. However if he decides to enter some values, then both fields must be entered and will require to have entered only whole positive numbers (from 0 to 4 million).
What am I doing wrong here?
In the end this did it:
pattern="^(\s*|\d+)$"
if ($('.txtminFeedback')[0].checkValidity()==false || $('.txtmaxFeedback')[0].checkValidity()==false) {
ShowMessage("Please enter only positive value for minimum and maximum feedback.");
return;
}
if ($('.txtmin')[0].checkValidity() && $('.txtmax')[0].checkValidity()) {
if ($('.txtSearch').val() == "") {
ShowMessage("Please enter the search term!");
return;
}
else {
PostAndUpdate($('.txtSearch').val(), $('input[name=type]:checked').val(), $('input[name=shipping]:checked').val(), $('input[name=condition]:checked').val(), $('.txtmin').val(), $('.txtmax').val(), $('.txtNegativeKeywords').val(), $('.txtminFeedback').val(), $('.txtmaxFeedback').val());
}
} else {
ShowMessage("You have entered incorrect value for minimum or maximum price!");
return;
}
Just in case someone in future might need it.
Cheers =)

How to set mobile number validation on my jsp page?

i am using this script for validation can anybody help me where i am wrong. i am using this foe mobile number validation.when i run this code with jquery it is not working.
function mobilenumber() {
if(document.getElementById('mobnum').value != ""){
var y = document.getElementById('mobnum').value;
if(isNaN(y)||y.indexOf(" ")!=-1)
{
alert("Invalid Mobile No.");
document.getElementById('mobnum').focus();
return false;
}
if (y.length>10 || y.length<10)
{
alert("Mobile No. should be 10 digit");
document.getElementById('mobnum').focus();
return false;
}
if (!(y.charAt(0)=="9" || y.charAt(0)=="8" || y.charAt(0)=="7"))
{
alert("Mobile No. should start with 9 ,8 or 7 ");
document.getElementById('mobnum').focus();
return false
}
}
}
<input type="submit" value="INSERT"class="btn"onclick="submitForm();">
jquery is
$(document).ready(function(){
function submitForm(){
if(mobilenumber()){
$('#form1').submit(function(){
});
}
else{
alert("Please Input Correct Mobile Numbers");
}
}
});
Use HTML5 Pattern
<input type="number" pattern=".{10}" title="Enter Valid Mob No" required>
var mobile = document.getElementById("mobnum").value;
var numericmob = isNumber(mobile );
if(!numericmob)
{
alert("Enter only positive numbers into the Contact Number field.");
return false;
}
if(mobile.length!=10)
{
alert("Enter 10 digits Contact Number.");
return false;
}
// write function that checks element is number or not
function isNumber(elem)
{
var re = /^[0-9]+$/;
str = elem.toString();
if (!str.match(re))
{
return false;
}
return true;
}
Advantage of this function is you can use it for checking any numeric field on your form, such as id, amount etc.
Use jQUery .submit() function to submit the form after validation is true
<form id="myForm" action="abc.php" method="post">
<!-- Your Form -->
<button onclick="submitForm();">Submit</button>
</form>
now to check if form data is valid here
function submitForm(){
if(mobilenumber()){
$('#myForm').submit();
}
else{
alert("Please Input Correct Mobile Numbers");
}
}
EDIT:
Use the #Aniket's isNumber function to check length and digit in mobile number field. Which is more generic.
if(document.getElementById('mobile_number').value != ""){
var y = document.getElementById('mobile_number').value;
if(isNaN(y)||y.indexOf(" ")!=-1)
{
alert("Invalid Mobile No.");
document.getElementById('mobile_number').focus();
return false;
}
if (y.length>10 || y.length<10)
{
alert("Mobile No. should be 10 digit");
document.getElementById('mobile_number').focus();
return false;
}
if (!(y.charAt(0)=="9" || y.charAt(0)=="8" || y.charAt(0)=="7"))
{
alert("Mobile No. should start with 9 ,8 or 7 ");
document.getElementById('mobile_number').focus();
return false
}
}
try this... this will be needful for you... and if you are looking for ragex pattern then use this....
^([0|\+[0-9]{1,5})?([7-9][0-9]{9})$

Limiting input field to one decimal point and two decimal places

I have an input field which is limited to 6 characters. How can I validate my input field so that a user can't put more than one decimal point (i.e. 19..12), plus it can only be to two decimal places as well (i.e. 19.123)?
This is my input field
<input type="text" name="amount" id="amount" maxlength="6" autocomplete="off"/><span class="paymentalert" style="color:red;"></span>
Here is my validation script.
$(function(){
$("#amount").keypress( function(e) {
var chr = String.fromCharCode(e.which);
if (".1234567890NOABC".indexOf(chr) < 0)
return false;
});
});
$("#amount").blur(function() {
var amount = parseFloat($(this).val());
if (amount) {
if (amount < 40 || amount > 200) {
$("span.paymentalert").html("Your payment must be between £40 and £200");
} else {
$("span.paymentalert").html("");
}
} else {
$("span.paymentalert").html("Your payment must be a number");
}
});
Jonah
This should do :
var ok = /^\d*\.?\d{0,2}$/.test(input);
(if I correctly understood that you don't want more than 2 digits after the dot)
The code thus would be :
$("#amount").blur(function() {
var input = $(this).val();
if (/^\d*\.?\d{0,2}$/.test(input)) {
var amount = parseFloat(input);
if (amount < 40 || amount > 200) {
$("span.paymentalert").html("Your payment must be between £40 and £200");
} else {
$("span.paymentalert").html("");
}
} else {
$("span.paymentalert").html("Your payment must be a number");
}
});
Assuming that:
There MUST have 2 digits after a decimal point, and
There must be at least 2 digits before the decimal point, but no more than 3 digits
The code you would use to match it would be:
var value = $(this).val;
value.match(/^\d{2,3}(\.\d{2})?$/i);
It would be much easier if you used the Masked Input Plugin for jQuery.

How to check value length with using Javascript?

Hello everyone I would like to ask how to check value's length from textbox ?
Here is my code :
#*<script>
function validateForm() {
var x = document.forms["frm"]["txtCardNumber"].value;
if (x == null || x == "" ) {
alert("First name must be filled out");
return false;
}
}
</script>*#
When I run my script yeap I got alert message but I'm trying to add property which control the texbox' input length.
You could use x.length to get the length of the string:
if (x.length < 5) {
alert('please enter at least 5 characters');
return false;
}
Also I would recommend you using the document.getElementById method instead of document.forms["frm"]["txtCardNumber"].
So if you have an input field:
<input type="text" id="txtCardNumber" name="txtCardNumber" />
you could retrieve its value from the id:
var x = document.getElementById['txtCardNumber'].value;
Still more better script would be:
<input type="text" name="txtCardNumber" id="txtCardNumber" />
And in the script:
if (document.getElementById(txtCardNumber).value.length < 5) {
alert('please enter at least 5 characters');
return false;
}

Categories