From this example
I tried to validate user input when a button was clicked.
$("#check_data").click(function () {
var $userInput = $('#user_input'); //from HTML input box id="user_input"
var pattern = " /*My user input always be like "AB1234567"*/ ";
if ($userInput.val() == '' || !pattern.test($userInput.val())) {
alert('Please enter a valid code.');
return false;
}
});
My user input input always be like "AB1234567" with this exact same characters but different 7 digits number.
I'm new to Javascript and Jquery, if you have any better way to validate user input, please suggest it.
Thank you.
You can use below regex Expression to check
/[A-Za-z0-9]/g
Your code could be like this
var _pattern=/[A-Za-z0-9]/g
if($userInput.val().match(_pattern))
{
//your code goes here..
}
Thanks
You can use the below pattern to check
/^AB\d{7}$/
You can change code to
var pattern = '/^AB\d{7}$/';
if ($userInput.val() == '' || !pattern.test($userInput.val()))
{
alert('Please enter a valid code.');
return false;
}
\d{7} matches 7 digits in the range [0-9]
You can follow below code for this:
if ($userInput.val().match(/[^a-zA-Z0-9 ]/g))
{
// it is a valid value.
} else {
// show error here
}
Hope it helps you.
Try this one.
$("#check_data").click(function(){
var $userInput = $('#user_input').val();
var pattern = /^AB[0-9]{7}?/g;
if(!$userInput.match(pattern)){
alert('Please enter a valid code.');
return false;
}
});
Related
I want to add an alert inside the if and else if. If the user does not enter anything in the prompt box the alert triggers. Also if the user enters a number the prompt it will say that the user entered a number. How do do that?
let myForm2 = document.querySelector('.form2');
let pDisplay1 = document.querySelector('.display4');
myForm2.addEventListener('submit', function(e) {
e.preventDefault();
let uname = document.querySelector('.inputName2').value;
if (uname == null) {
} else if (isNaN(uname) == false) {
} else {
pDisplay1.innerHTML = `Welcome to the program ${uname}`;
}
})
<p> Activity 6</p>
<form class="form2" method="get">
<label>Full Name: <input type="text" class="inputName2"></label>
<input type="submit">
</form>
<p class="display4"></p>
document.querySelector('.className').value will return a string.
string.trim() removes the whitespaces and if the length === 0 it means that the input is empty or has only whitespaces which you generally want to treat as empty. If you consider space is a valid input you don't have to use trim().
The + sign will convert a string into a number otherwise you could use parseInt(variable).
Number.isInteger(variable) will return true if the variable is an integer.
You could also write !isNaN(+uname) or +uname !== Number.NaN
myForm2.addEventListener('submit', function (e) {
e.preventDefault();
let uname = document.querySelector('.inputName2').value;
if (uname.trim().length === 0) {
alert('You should write something');
} else if (Number.isInteger(+uname)) {
alert('You wrote a number');
} else {
pDisplay1.innerHTML = `Welcome to the program ${uname}`;
}
});
Empty string is not equal to null, replace uname==null with uname=='', after the replacement, you can identify the situation that the user did not input, if it is more strict, you can also use trim to remove whitespace and then do condition review
I'm in the process of creating a gambling website, but currently with the betting form input you can type a negative number etc (-100) and you will have 100 coins put into your balance.
I need to restrict the use of anything but number digits being used within the input. Currently my work around is blocking the user from typing in anything other than numbers but you are able to hop into the developer tools and insert the value manually.
I believe i need to have an onSubmit validation for the input which says if anything but numbers are inserted do not allow the submit.
I'm not sure how i will do this, thanks for the help!
put onkeypress="return onKeyValidate(event,alpha);" on your input box,and
call the function
function onKeyValidate(e,charVal){
var keynum;
var keyChars = /[\x00\x08]/;
var validChars = new RegExp(charVal);
if(window.event)
{
keynum = e.keyCode;
}
else if(e.which)
{
keynum = e.which;
}
var keychar = String.fromCharCode(keynum);
if (!validChars.test(keychar) && !keyChars.test(keychar))
{
return false
} else{
return keychar;
}
}
Use ctype_digit()
//returns true
<?php
if (ctype_digit('123')) {
echo 'true';
} else {
echo 'false' ;
}
?>
//returns false
<?php
if (ctype_digit('-123')) {
echo 'true';
} else {
echo 'false' ;
}
?>
you can use this reguler expression to validate for numbers
samp html <button type="submit" onclick="myfunc()">Click Me!</button>
function myfunc(){
var a = /^\d*$/;
{
if(!a.test(value of input))
{
alert('Please provide a Number');
return false;
}
}
}
here
/ at both ends mark the start and end of the regex
^ and $ at the ends is to check the full string than for partial matches
d* looks for multiple occurrences of number charcters
if you want only positive numbers use this/^[+]?([0-9]+(?:[\.][0-9]*)?|\.[0-9]+)$/
this jquery code can solve your problem
$(function(){
$("#submit").click(function(evnt){
var inptTxt = $("#myField").val();
if(check(inptTxt)){
//your test true then submits
$('#form').submit;
}else{ //test failed
evnt.preventDefault();
}
})
})
here the #submit is the id of submit button and #form is the id of the form to be submitted
Hi i have created a javascript function to only allow numbers between 0 to 30 and character A and D. I give an alert if it does not match the criteria but if the user clicks ok on the alert the values still remain in the input and can be updated in the database. I want that user should not be able to enter anything at all in the input box except character A , D and numbers between 0 to 30 like it is done in the case of input type=number we can only enter numbers. My javascript function is:-
function validate() {
var regex = /[ad0-9]/gi;
var txt = document.getElementById('txt').value;
var valid = true;
var error = '';
if (regex.test(txt)) {
if (!isNaN(txt)) {
if (!(parseInt(txt) >= 0 && parseInt(txt) <= 30)) {
valid = false;
error = 'Please enter between 0 to 30.'
}
}
}
else {
valid = false;
error = 'Please enter between 0 to 30, A or D'
}
if (!valid) {
alert(error);
}
}
The javascript works fine with validation but after clicking ok in alert value still remains there and it also gives error when input box is empty any way to avoid that. Is there any other better way to create the function or can it done by using jquery. I am new to jquery if it is possible to do it with jquery it would be great. I would be highly gratefull if anybody can help.
You may try this code example.
function validate(box) {
var val = box.value;
if (!/^[AD]?$/.test(val) && isNaN(val) || (0 > val || 30 < val)) {
box.value = '';
alert('Only A or D or 0-30');
}
}
<input type='text' value='30' onblur='validate(this);' />
The best solution would be to check it at the moment when you are inserting it in the database.
if(txt.replace(/ /g, '').length == 0) {
// text is empty
return; // get out of function
}
If you want to make sure there is no error when the text is empty, you can do this. The .replace part is to ensure that if the text input is filled with only spaces, it is considered empty.
With the rest of the function:
function validate() {
var regex = /[ad0-9]/gi;
var txt = document.getElementById('txt').value;
var valid = true;
var error = '';
if(txt.replace(/ /g, '').length == 0) {
// text is empty
return; // get out of function
}
if (regex.test(txt)) {
if (!isNaN(txt)) {
if (!(parseInt(txt) >= 0 && parseInt(txt) <= 30)) {
valid = false;
error = 'Please enter between 0 to 30.'
}
}
}
else {
valid = false;
error = 'Please enter between 0 to 30, A or D'
}
if (!valid) {
alert(error);
}
}
How about replacing disallowed values so only the desired input is allowed. With this you won't be able to enter anything other than A, D and numbers 0 - 30:
$('input').on('input', function(e) {
this.value = this.value
.replace(/[^AD\d]/, '')
.replace(/(3)[1-9]/, '$1')
.replace(/(30)[0-9]/, '$1')
.replace(/([4-9])[0-9]/, '$1')
.replace(/([\d][\d])[\d]/, '$1');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="text" />
Note, it's still a good idea to do some server side validation.
I have the following validation code on my .asp webpage. I also need to validate the txtndc textbox so that the data entered looks like this. 00000-0000 Currently they can enter any info in this textbox. The entry should always be 5 numbers a dash and 4 numbers. Any help would be greatly appreciated.
function form_onsubmit() {
if (form1.txtdrug.value == "")
{
alert("Drug Name Needed");
return false;
}
if (form1.txtndc.value == "")
{
alert("NDC Number Needed");
return false;
}
if (form1.txtndc.value != "" && form1.txtdrug.value != "")
{
alert("Drug was Successfully entered into the database, hit enter to continue.");
return true;
}
}
How would the syntax be written. The textbox i am trying to check is
<input type="text" name="txtndc" size="35">.
I am not sure how to enter your code below above into my page. Please Help
Using Javascript regex#test function.
x = /^[0-9]{5}-[0-9]{4}$/;
console.log(x.test("12113-1234"));
>>> x = /^[0-9]{5}-[0-9]{4}$/; console.log(x.test("00000-0004"));
true
Demo: http://jsbin.com/axikiv/1/edit
My validation function looks like that.
var fname = $("#fname").val();
var lname = $("#lname").val();
function validate() {
var isValid = true;
if (!fname) {
$("#fname").attr('class', 'invalid');
isValid=false;
}
if (!lname) {
$("#lname").attr('class', 'invalid');
isValid=false;
}
It simply changes the class of unfilled input box.
I know that i can write else for every if and change back to default (class="valid") if user fills some of inputs. But how can i create something universal for all inputs to change back to default class the input that user has filled after first validation error?
That was good Tural! HOWEVER, why the excess processing in your code? That will add unecessary stress. Since you, for what you "solved", will add the "valid" class to ALL the input type text or password, just add that to the actual input element in the straight code:
<input class='valid' ..... />
Now, back to your original validation: why not make it universal?:
function validate(formField) {
if !formField $('#'+formField).removeClass('valid').addClass('invalid');
}
Or something in that vein ...
You can either assume everything is valid and then try to disprove that or you can try to prove its validity. The below takes the first approach and sets all the classes to "valid" to be consistent with that.
function validate() {
// Get the current form input state.
var fname = $("#fname");
var lname = $("#lname");
// Assume everything valid until proven otherwise.
var isValid = true;
fname.attr('class', 'valid');
lname.attr('class', 'valid');
if (!fname.val()) {
fname.attr('class', 'invalid');
isValid=false;
}
if (!lname.val()) {
lname.attr('class', 'invalid');
isValid=false;
}
return isValid;
}
Ok. I found the way
$('input[type="text"],input[type="password"]').keypress(function () {
$(this).attr('class', 'valid');
});