I have 5 text boxes I will get prices how can I validate there is only numbers on those text boxes if there is a letter I want to give a alert when submit.
How can I do that please help me Im new to these stuff
<input type="text" id="sellingPrice"><br>
<input type="text" id="basicPrice"><br>
<input type="text" id="latestBuyingPrice"><br>
<input type="text" id="ReorderQuantity"><br>
<input type="text" id="reorderLevel"><br>
<button id="save_P" type="button" class="save-button-text save-button displayShow" onclick="submitDetails()">
how can I use number validation in submitDetails() method
This is a pretty common issue, but there are a couple ways to approach it:
Verify using Regular Expressions
Attempt to parse the number and check if isNaN(parsedResult) returns true
By far, I believe the most common approach is var num = parseFloat(StringNumberFromTextbox), isValidNumber = (!isNaN(num) && isFinite(num));
If you went the RegEx route, you could use: var rNumPattern=/^\d+(\.\d+)?$/, isValidNumber = rNumPattern.test(StringNumberFromTextbox);
You might also consider consider checking negative/positive signs and thousands separators using replacements of commas or periods (as appropriate for the locale/clientele).
Of course, if you are then submitting those on a form to some backend processor, you would be wise to check those numbers again on the server-side rather than blindly trusting that the client has provided valid numbers just because your JavaScript should done the checking. Lest you end up with a SQL vulnerability or the like.
You can add type="number" attribute to input tag.
In submitDetails() use following code.
var sellingPrice=document.getElementById("sellingPrice").value;
//repeat above code for all field.
if(Number.isInteger(sellingPrice) == false){
alert('wrong value entered');
}
//repeat above if code for all value.
This will do what you want.
You can check it using isNaN(value) inbuilt function of JavaScript.
Your function could be like this:
function submitDetails() {
var val = document.getElementById("sellingPrice").value;
if (isNaN(val)) {
// show alert here
}
}
Related
Could anyone help with this?
Code allowing the user to input a username and a password, both of which must be validated as follows:
The username may only contain letters, dots (.), the at sign (#). The username must NOT be longer than 25 characters.
In order to limit to 25 characters, the easiest way is to use an
<input type="text" maxlength="25" />
In order to validate that input only contains letters, dots (.) and #, proceed with a regular expression.
Example:
<input id="input" type="text" maxlength="25" />
<button id="button">Test</button>
<br/>
<div id="validation" />
$(document).ready(function(){
var $text = $('#input');
var $btn = $('#button');
var $out = $('#validation');
$btn.on('click', _do_check);
function _do_check(e){
e.preventDefault();
e.stopPropagation();
var text = $text.val();
if (/^[a-zA-Z.#]+$/.test(text) ){
$out.html('OK');
} else {
$out.html('FAILURE');
}
}
});
Hope this helps.
Using only plain Javascript:
You will need to construct a regular expression. Check this to get an idea how it works in Javascript https://www.w3schools.com/jsref/jsref_obj_regexp.asp
The following expression would be a regular expression fitting your username requirements with the only allowed characters and the length restrictions at once
/^([a-zA-Z\.\#]{1,25})$/
You can play and learn how to build a regular expression with pages like https://regexr.com/
And as recommended you should start with some of your work in order to help actually with a problem and then the community can guide you to solve your real issue.
How would integrate text as an argument for my if statement to function?
function ifStatement() {
var userInput = document.getElementById("userBlank").value;
if (userInput > 9) {
return alert("Please enter a correct value");
} else {
document.write("you may enter");
}
}
<form id="form" onsubmit="return false;">
<input type="button" value="click" onclick="ifStatement();">
<input id="userBlank" type="text">
</form>
As seen here, I want my if statement to be triggered off of text as well as numbers less than 9. Is it possible to do that?
I tried putting text into the input blank however it did not trigger the if statement.
IIUYC, you can achieve that without JS using number input type:
<input id="userBlank" type="number" min="0" max="9" required>
It won't allow you to enter anything besides digits and input's value will be checked on submit so it's not less than 0 and not greater than 9.
Freshly tried:
function ifStatement() {
var userInput = document.getElementById("userBlank").value;
if ( (isNaN(userInput)) || ((!isNaN(userInput)) && (userInput > 9)) ) {
console.log("Please enter a correct value");
} else {
console.log("you may enter");
}
}
You should check your data types
document.getElementById("userBlank").value
is going to return a string but you want to compare it with a number.
Try to normalize your data contained in 'userInput' first maybe using something like parseInt() so you can compare these two values.
You can use the pattern attribute to create custom validation. To check whether it's a single digit number, you can use the regular expression \d (short for digit). You can use the title attribute to add a custom tooltip message when validation fails and you can use the required attribute to ensure this field isn't blank. In the end, this looks like:
<form onsubmit="alert('success');return false">
<input type="text" pattern="\d" required="required" title="A single digit number is required" />
<input type="submit" />
</form>
In Javascript you can test input values by using regex, but as already noted HTML5 does much of this for you; Giving no reason to do it in javascript for on page form testing.
But it is still useful for testing query string data on the URL, localStorage data, or cookie data.
function ifStatement() {
var userInput = document.getElementById("userBlank").value;
if (/[0-9]/.test(userInput)) {
alert("You entered: " + userInput);
} else {
alert("Enter a number");
}
}
Also note, javascript testing on the page does not protect the server from bad user input data. Anyone can simply go into inspect page tools and remove the test and allow bad data to be sent to a server.
So I have to get an input value in attr=value format.
Something like name=John or surname=Doe. The string could contain number but no symbol other then = is allowed.
Now, I need to validate the field in Javascript. I have already got a regex, which goes something like this /[a-zA-Z0-9]+[=]+[a-zA-Z0-9]+/. Its working fine. However, I feel like there might be a better regex to do this. Also, if user inputs something like name=John-, it allows it. Which should not be the case. If you guys could point me to the right direction, it would be great.
var regexField = $('#regex-test'),
RegEx = /[a-zA-Z0-9]+[=]+[a-zA-Z0-9]+/,
isValid = function(element){
return RegEx.test(element.val());
};
$('#submit').click(function(e){
if(isValid(regexField)){
$('#err').hide();
return;
}
$('#err').show();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="err" style="display:none">
Please enter proper value!
</div>
<input type="text" id="regex-test" required/>
<button id="submit">Submit</button>
Your expression is not far off from what you want. The reason it's allowing name=John- is because there is no anchoring to the ends of the string. It will also accept, for example, #$%name=John-!?foo. To anchor to the start use ^ and $ for the end.
You don't need to put the = in a character class (as you've only got one option); and you definitely don't want to quantify it with + as you want exactly one (not one or more).
Finally, you can simplify it a little bit by making it case-insensitive, using the i flag.
Ultimately, this gives you:
/^[a-z0-9]+=[a-z0-9]+$/i
You can make it even simpler if you allow underscores in your attributes and values: then you can change [a-z0-9] to \w...but that's your call :)
A version that allows whitespace around the =, and allows only whitespace after the name=value portion (and so disallows symbols at the end), would be:
RegEx = /\s*[a-z0-9]+\s*=\s*[a-z0-9]+\s*$/i
var regexField = $('#regex-test'),
RegEx = /\s*[a-z0-9]+\s*=\s*[a-z0-9]+\s*$/i,
isValid = function(element){
return RegEx.test(element.val());
};
$('#submit').click(function(e){
if(isValid(regexField)){
$('#err').hide();
return;
}
$('#err').show();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="err" style="display:none">
Please enter proper value!
</div>
<input type="text" id="regex-test" required/>
<button id="submit">Submit</button>
I'm finishing a form I have to do for my homework, and just when I thought I was finished, I found a mistake.
I need a RegEx for input field that would return an alert if there's not exactly 13 digits.
While I know the correct RegExp for this is: /^\d{13}$/, I also need it to ignore an empty field. (Because I don't want the alert to trigger in case the user switches to a different input field)
Just when I thought I had it with: /^$|\d{13}$/, it turns out that it will return an alert if there are less than 13 digits but not if there are more, unlike /^\d{13}$/ that is working fine with 14+ digits.
Can someone help me out with this? Thanks
Here's the rest of the function:
function checkNum(box) {
var re= new RegExp(/^$|\d{13}$/);
if(!box.value.match(re)) {
alert("13 numbers are required");
document.getElementById("numbers").value = '';
}
}
And here is the input field:
<input type="text" name="numbers" id="numbers" placeholder="Numbers" onFocus="this.placeholder=''" onBlur="checkNum(this); this.placeholder='Numbers'"/>
Very close!
/^$|^\d{13}$/
You just forgot to specify that the 13 digits started at the start of the string
Also, just an alternative to match(), for quicker boolean check use test()
if (!/^\d{13}$/.test(box.value)) {
alert("13 numbers are required");
document.getElementById("numbers").value = '';
}
I have not found a good solution: I have a text box in which users need to be able to type specific info into. For example the command might be "9030 OUT FU [1234 TEST]". I need to "scrub" this text box to ensure that the data was typed in exactly this format (caps not necessary). However there are approximately 50 of these different types of commands.
I am fairly new to javascript, but with good direction can understand it. Is this possible with javascript? Once the data is entered into the text box, it will run a function to return some information, and the text box will be clear for the next command. No 2 commands can be entered at the same time. I just need to check the format is 100% accurate for each command. Any help is appreciated, thank you.
<script type="text/javascript">
function scrub(text) {
var commands = new Array{"someCommand","anotherCommand",...};
for (var i = 0; i <= commands.length; i++) {
if (text.value.toLowerCase().equals(commands[i])) {
//command is valid; do something here
} else {
alert("Invalid command");
}
}
text.value = ""; //clears the text box
}
</script>
For your textarea do this:
<textarea onblur="scrub(this);" ...></textarea>
Is there a set of keywords? And can be they be combined only in a certain fashion?
Looks like couple of regex patterns will be able to do the trick.
e.g: to match "9030 OUT FU [1234 TEST]" regex would be: /\d{4} OUT FU \[\d{4}\]/.
OUT FU and can be substituted with \w{3} and \w{2} respectively (unless you do not want any word to be allowed).
Use regular expressions.
html:
<input type="text" id="code" />
<input type="button" value="test" onclick="alert(checkCode())" />
javascript:
function checkCode(){
var code = document.getElementById('code').value;
return code.match(/\d+ \w+ \w+ \[\d+ \w+\]/)!=null ? true : false;
}
http://gskinner.com/RegExr/ is very helpful with regular expressions.
When you say "exactly this format", you have to understand that we have no clue what you mean. There are an infinite number of patterns that could be used to describe your example. The regular expression above will match if the code has a string of numbers, then a word, then another word, then an opening bracket, then a string of numbers, then a word, then a closing bracket.