Validating a field before submitting - javascript

I have a text field and a button.
I want to validate the field, and if the validation fails, the button should not "submit".
This is my button:
<input type="submit" onsubmit="return validate()"
And this is my validation function:
function validate()
{
var number = document.getElementById("temp");
alert (number.value);
if ( /^[0-9]{12}$/.test(number.value) )
{
alert(number);
return true;
}
alert ("מספר הפנייה חייב להיות בן 12 ספרות");
return false;
}
But it wont work, the submit occures any way.
Any ideas?

The onsubmit event should be attached to the form object, not the submit button.

It should be like this:
<form id = "myform" onsubmit="return validate()" action = "mypage.php">
<input type="submit">
</form>
This should work...

Related

calling a method if the validation function is true

When the submit button is pressed, my validation function should check if the fields are validated then call the setProfile method. currently when i click the submit button it will not validate my fields so something must be wrong
<form name="Login" method="post" action="#" onsubmit="return validateForm()">
<input type="text" name="fName" id="name"> <br>
</form>
<input type="submit" name="Update" value="Update">
function validateForm() {
var n = document.forms['Login']['fName'].value;
if(n==null || n=="")
{
alert("Please enter your name");
return false;
}
return true
}
function UpdateProfile() {
document.querySelector('submit').addEventListener('click', e=>{
const myProfile = new Profile
if (e.validateForm === true){
myProfile.setProfile();}
})
}
The most likely reason for your code not working is that your validateForm() function is not getting called at all on submit button press. To find out if that's the case, the simplest thing to do is to add an alert() at the top of the validateForm() function.
If it's indeed not called, google "call javascript function on button click" for a code sample. Here's one: Using an HTML button to call a JavaScript function

Stopping submitting when alert is shown

I have form that has text input and submit. I'm trying to show an alert with Javascript if input is empty.
This is my code:
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, "");
}
function emptyArea() {
if (document.getElementById("type-text").value.trim() == '') {
alert("Please fill all fields");
} else("OK");
}
<form>
<input id="type-text" type="text" placeholder="Type some text">
<input type="submit" placeholder="Submit" onclick="emptyArea()">
</form>
When I click submit and it is empty, form still submits and doesn't show the alert. How would I prevent it from submitting and instead show an alert?
When I run your code, I actually do get alerts when I click "submit". Are you sure you are attaching the event handler correctly? I'm guessing maybe what's actually happening is that the alert is showing but then it submits anyway no matter if the form value is valid.
If you want to prevent the form from submitting, call e.preventDefault() where e is the event object which will be passed as the first argument to your handler function.
Here is an example codepen:
https://codepen.io/quinnfreedman/pen/PoqmGYb
function emptyArea(e) {
if (document.getElementById("text").value.trim() == '') { // .trim is supported by browsers since IE9
alert("Please fill all fields");
// the conditions were not met, so call preventDefault to
// stop the browsers default behavior of submitting the form
e.preventDefault();
e.stopPropagation();
} else {
// If we don't preventDefault, the form will submit after this alert
alert("OK")
}
}
document.getElementById("Submit").addEventListener("click", emptyArea)
<form action="#">
<input type="text" id="text" />
<input type="submit" id="Submit" />
<!-- NEVER call anything "submit" in a form -->
</form>

Avoid page submission on button click if condition false in javascript

I am checking the textbox value in javascript. and saving to database. where as my save is of submit type. I want if textbox value is greater than 100 then it should alert. and after alert , page should not submit.
Firstly, bind the click event of that button to a function. Secondly, use event.prevent default to stop that button from submitting the form. Thirdly, validate the value you want. If validated, use form id to submit the form. Something like this:
$("#ButtonId").on("click", function(event) {
event.preventDefault ? event.preventDefault() : event.returnValue = false;
if ($("#InputBoxID").val() < 100) {
$("#FormId").submit();
}
else {
alert("your message");
}
});
Above code is in jQuery, so do not forget to add the reference to jQuery.
I think you're looking for something like:
<form id="myForm" onsubmit="return validateForm();">
<input type="text" id="textfield"/>
<button type="submit">submit</button>
</form>
<script>
function validateForm(){
var value=parseInt(document.getElementById('textfield').value);
if(value>100){
alert('value is no good. larger then 100');
return false;
}
}
</script>
If you can show me your code I'd be happy to help you implementing such a feature.
Here you have an example of how to do it. I used a limit of 10 characters to make the test easier: Try if yourself
HTML:
<input type="text" id="myTextBox" onkeyup="checkValue(this)" maxlength="10"></input>
<input id="sendButton" type="submit" value="SEND"></inpu
JAVASCRIPT:
function checkValue(textbox) {
if (textbox.value.length > 10) {
alert("TEXT TOO LONG");
document.getElementById("sendButton").disabled = true;
}
else
document.getElementById("sendButton").disabled = false;
}

Stop form from submitting when it doesn't validate

The validation works, and the alert pops up when the email address is not valid, but then it goes and submits it after you click 'Ok' anyway. How do I stop it from processing the action?
Code sample:
<input type="submit" onclick="validate()" />
function validate() {
var email = $('input[name=email]').val();
if (!/(.+)#(.+){2,}\.(.+){2,}/.test(email)) {
alert('Please enter a valid email address');
return false;
}
}
Thanks!
onclick="return validate();"
then return true if validation is successful and false if not...
you can also attach the validation to the form itself:
<form onsubmit="return validate();">
or with jquery:
$('form').submit(function() {
// validate
});
You need to bind onsubmit event of the form tag i.e.
<form onsubmit="return validate();" >...</form>

Clear an input field after submission using JavaScript

I am a JavaScript newbie. I have an input text field that I wish to clear after pressing the form submit button. How would I do that?
In your FORM element, you need to override the onsubmit event with a JavaScript function and return true.
<script type="text/javascript">
function onFormSubmit ()
{
document.myform.someInput.value = "";
return true; // allow form submission to continue
}
</script>
<form name="myform" method="post" action="someaction.php" onsubmit="return onFormSubmit()">
<!-- form elements -->
</form>
If a user presses the submitbutton on a form the data will be submitted to the script given in the action attribute of the form. This means that the user navigates away from the site. After a refresh (assuming that the action of the form is the same as the source) the input field will be empty (given that it was empty in the first place).
If you are submitting the data through javascript and are not reloading the page, make sure that you execute Nick's code after you've submitted the data.
Hope this is clear (although I doubt it, my English is quite bad sometimes)..
function testSubmit()
{
var x = document.forms["myForm"]["input1"];
var y = document.forms["myForm"]["input2"];
if (x.value === "")
{
alert('plz fill!!');
return false;
}
if(y.value === "")
{
alert('plz fill the!!');
return false;
}
return true;
}
function submitForm()
{
if (testSubmit())
{
document.forms["myForm"].submit(); //first submit
document.forms["myForm"].reset(); //and then reset the form values
}
}
First Name: <input type="text" name="input1"/>
<br/>
Last Name: <input type="text" name="input2"/>
<br/>
<input type="button" value="Submit" onclick="submitForm()"/>
</form>
After successfully submitting or updating form or password you can put empty value.
CurrentPasswordcontroller.state.confirmPassword = '';

Categories