How use liferay validator with js submit? - javascript

I try to use Liferay validator with javascript on Liferay 6.2.
Have a problem is my button must using submit form with a button onlick, but when submit this way Liferay form validator no trigger prevent submit. It just triggers when I using a button type submit.
Here mycode example:
<portlet:actionURL name="updateURL" var="submitURL"/>
<aui:form name="fm2" id="fm2" action="<%=submitURL %>" method="post">
<aui:input name="userName" value='' label="User Name"></aui:input>
<aui:input name="password" value='' label="Password"></aui:input>
<aui:button type="button" name="logIn" id="logIn" value="Login" />
</aui:form>
<aui:script>
AUI().use('aui-base','liferay-form','aui-form-validator',function(A){
A.one("#<portlet:namespace/>logIn").on("click",function(){
submitForm(document.<portlet:namespace />fm2);
});
Liferay.Form.register(
{
id: '<portlet:namespace/>fm2',
fieldRules: [
{
body: '',
custom: false,
errorMessage: '',
fieldName: '<portlet:namespace/>password',
validatorName: 'required'
},
{
body: '',
custom: false,
errorMessage: '',
fieldName: '<portlet:namespace/>userName',
validatorName: 'required'
}
]
});
});
</aui:script>
What i can do ?
How to liferay can prevent event submit with tag, but does not with js?
Here is AUIFormValidator-portlet to demo.
https://drive.google.com/open?id=0B27gY2oYFX7QTTFFdXc3TnZ4d1k

You can do one thing,
<aui:form name="fm2" id="fm2" action="javascript:void(0)" method="post">
It will prevent your submit event and fire the aui form validation.
Now in onClick function you can assign your submit url to form action like below.
$("#<portlet:namespace/>logIn").on("click",function(){
var url = '${submitURL}';
$('#<portlet:namespace />fm2').attr('action', url);
$('#<portlet:namespace />fm2').trigger("submit");
});

Related

jQuery validate only get triggered on the second submit

I have the jquery validation function in the javascript which will get called from react js function.
React JS
function handleFormSubmit(e){
e.preventDefault()
window.validateForm();
}
return (
<form id="contactForm" onSubmit={handleFormSubmit} novalidate="novalidate">
<input name="name" id="name" type="text" placeholder="Name" onChange={handleInputChange} />
<textarea name="address" id="address" cols="4" rows="4" placeholder="Address" onChange={handleInputChange}></textarea>
<button type="submit">Submit</button>
</form>
)
JavaScript
function validateForm(){
$("#contactForm").validate({
rules: {
name: { required: true },
address: { required: true }
},
messages: {
name: { required: "Name field is required" },
address: { required: "Address field is required" }
}
});
}
The first submit is calling the validateForm() function but it won't trigger the jquery validate(). It only get triggered on the second submit click.
The reason is because you are assigning the Validation on the first click. It assigns its own event listener. The second click runs it and you also reassign the validate code again.
You need to just call the code on document ready. So get rid of the on submit
I have the jQuery validation function in the javascript which will get called from react js function.
$(function () {
window.validateForm();
});
And seeing you are using jQuery with React, it is a bit more complicated than that.

VueJS prevent form submission on submit and submit the form on keyup

I have a form that looks like this:
<form id="myForm" action="/searchuser" method="POST" #submit.prevent="onSubmit(inputValue)">
<div class="field">
<label class="label">Name</label>
<div class="control">
<input class="input" type="text" placeholder="Text input" v-model="inputValue" #keyup="onKeyUp" #blur="inputFocused = false">
<ul v-if="inputFocused">
<li v-for="value in values"><a class="panel-block is-primary" :href="value.link">#{{value.title}}</a></li>
</ul>
</div>
</div>
</form>
And in my JavaScript, I have two methods onSubmit and onKeyPress:
<script>
export default {
data() {
return {
inputValue: "",
inputFocused: false,
values: [
{ title: "facebook", link: "http://facebook.com" },
{ title: "twitter", link: "http://twitter.com" },
{ title: "gplus", link: "http://plus.google.com" },
{ title: "youtube", link: "http://youtube.com" }
]
};
},
methods: {
onKeyUp: function() {
document.forms["myForm"].submit();
this.inputFocused = true;
},
onSubmit: function(inputval) {
console.log(inputval);
}
}
};
</script>
What I am trying to achieve is when the user presses a key, I want the form to be submitted but I don't want the page to be redirected to /searchuser route. But as soon as I press a key, the page gets redirected even though I am using the prevent modifier to prevent the submission. How do I prevent it from being redirected and submit it on keyup/keydown only? My goal is to perform an ajax call through onSubmit by sending the inputval to the server.
Vue is not overriding the DOM default behavior, if you decide to
access the DOM API directly while bypassing vue mechanics (e.g.
document.forms)
If you want to submit a form without the redirection, you have to do
ajax request.
you have to use axios (my personal choice). because you are trying to submit the form directly ...in order to keep up with the default form submission data format, I assume you need to sereialize the data as application/x-www-form-urlencoded format. check the docs.
see the code:
onKeyUp method:
onKeyUp: function() {
axios.post("/searchuser", qs.stringify({ inputValue: inputValue }));
this.inputFocused = true;
},
Remember to add axios and qs to your dependencies using npm, and import them on the file.

Bootbox incorrectly submits a form when a single input field is present

I have a strange problem that's really starting to bug me. Apologies in advance for a wall of code and somewhat confusing question.
I need to display a modal form for the user, and have them fill in some details.
The user can click Save to save their changes.
The user can click Cancel to cancel their changes.
I use the save handler to serialize the form and send its data to a JSON service.
If I have a form with multiple input fields, it all works great, and nothing unexpected happens.
If I have a form with a single input field, however, I get an unexpected side-effect. Hitting Enter/Return in that input field causes the modal form to be submitted, and instead of my JSON handler getting called the page is reload with the form's arguments as parameters — exactly as if the form is being submitted. In fact, adding an action= parameter to the form element has proven that, as you get navigated to the page you specify.
Here's the form I'm using:
<form id="surveyQuestionForm" class="form-horizontal" style="display:none;">
<div class="row">
<input name="surveyQuestionId" id="surveyQuestionId" type="hidden">
<input name="surveyId" type="hidden" value="${survey.surveyId}">
<div class="control-group">
<label class="control-label" for="questionType"><b><spring:message code="survey.question.type"/></b></label>
<div class="controls">
<select class="input-large" name="questionType" id="questionType">
<option value="">(Select one)</option>
<c:forEach items="${surveyQuestionTypes}" var="surveyQuestionType">
<option value="${surveyQuestionType.code}">${surveyQuestionType.name}</option>
</c:forEach>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="questionText"><b><spring:message code="survey.question.text"/></b></label>
<div class="controls">
<input type="text" class="input-xlarge" name="questionText" id="questionText" maxLength="64"/>
</div>
</div>
</div>
</form>
and here's the code I use to display the form modally:
function addQuestion() {
// find the form, and initialise its validation.
var form = $('#surveyQuestionForm');
var validator = form.validate(
{
rules: {
questionType: {
required: true
},
questionText: {
required: true
}
},
messages: {
questionType: {
required: '<spring:message javaScriptEscape="true" code="survey.question.type.required"/>'
},
questionText: {
required: '<spring:message javaScriptEscape="true" code="survey.question.text.required"/>'
}
},
onkeyup: false
});
// reset form validation, and hide any error message
validator.resetForm();
$("#errorMessage").hide();
// show the dialog
bootbox.dialog({
title: '<i class="icon-plus green"/> <spring:message javaScriptEscape="true" code="survey.add.question"/>',
message: form,
closeButton: false,
buttons: {
cancel: {
label: '<i class="icon-remove bigger-130"></i> <spring:message javaScriptEscape="true" code="button.cancel"/>',
className: "btn btn-danger"
},
save: {
label: '<i class="icon-ok bigger-130"></i> <spring:message javaScriptEscape="true" code="button.save"/>',
className: 'btn btn-success',
callback: function () {
var result = false;
if (!form.valid())
return false;
$.ajax({
type: "POST",
url: '/addSurveyQuestion.json',
async: false,
data: form.serialize(),
success: function (outcome) {
if (outcome.success) {
$('#question-list').dataTable().fnReloadAjax();
result = true;
}
else {
$("#errorMessage").html(htmlEncode(outcome.message)).show();
}
}
}
).fail(function () {
$.gritter.add({
title: '<spring:message javaScriptEscape="true" code="general.error"/>',
text: '<spring:message javaScriptEscape="true" code="server.error"/>',
class_name: 'gritter-error'
}
);
}
);
return result;
}
}
},
show: false,
animate: false,
onEscape: false
}
).on('shown.bs.modal', function () {
var form = $('#surveyQuestionForm');
form.find('#surveyQuestionId').val(null);
form.find('#questionType').val('');
form.find('#questionText').val('');
form.show().find('#questionType').focus();
form.show();
}
).on('hide.bs.modal', function (e) {
if (e.target === this)
$('#surveyQuestionForm').hide().appendTo('body');
}
).modal('show').addClass("bootboxDialog40");
}
If I use this code as-is, with Bootbox 4.4, hitting Enter/Return while the user is in the questionText field submits the form, and my page redisplays but with the form fields as parameters, eg:
page.html?surveyQuestionId=&surveyId=3&questionType=Y&questionText=blah
If I have a second input field, hitting Enter/Return in the fields does nothing, and the user has to click Save or Cancel.
Submit-on-enter for a single input field is a browser behavior that you will need to override. You can do this a few ways.
<form onSubmit="return false;">
I don't think you are using the native submit function at all, so adding this bit of inline scripting prevents the form submission. But putting scripts in your markup isn't great. A little jQuery can do the same thing for you:
$('form').on('submit', function(){ return false; });
I believe this is not related to bootbox plugin. The actual reason is here:
https://www.w3.org/MarkUp/html-spec/html-spec_8.html#SEC8.2
When there is only one single-line text input field in a form, the user agent should accept Enter in that field as a request to submit the form.
Coming to the solution, you can add another hidden field in your form which will prevent the submission of the form on enter.

JQuery validation form but not `submit` button

I'm using the JQuery.Validation plugin to validate some fields in a form, but I don't want to use a submit button, I want to use just an <input type="button"> and once clicked using JQuery I want to call my controller, the only thing is that it's not a submit button, so even if the fields are wrong or not validated it will call the controller even if the fields values are wrong, because I'm using the .click() event of JQuery when that button is clicked, I want when I have wrong values on the fields and the validation is showing an error message not to call my action controller even if the button is clicked, how can I reach this?
This is my html code:
<script src="~/js/jquery.validate.js"></script>
<form action="post" class="rightform newsletter" id="formSubscription">
<div class="title">
<img src="http://ligresources.blob.core.windows.net/public/UK/Content/Images/newsletter.png" alt="">NEWSLETTER
</div>
<input type="text" id="txtFullName" name="fullName" placeholder="Full name" required>
<input type="email" id="txtEmail" name="email" placeholder="Email address" required>
<button type="button" id="btnSubscription" data-url="#Url.Action("SubscriptionEmail","Email")" style="background-color:#f66804;">SUBSCRIBE TO NEWSLETTER</button>
</form>
This is the JQuery.Validation plugin code:
$(document).ready(function () {
$("#formSubscription").validate({
rules: {
email: {
required:true,
email:true
},
fullName: {
required:true
}
},
messages: {
email: {
required: "Please enter an email address",
email: "Please enter a valid email address"
}
}
});
});
And this is the JQuery function that I have for the moment to throw when the btnSubscription is clicked:
$(document).ready(function () {
$("#btnSubscription").click(function () {
SendSubscription();
}),
return false;
}),
function SendSubscription() {
$.ajax({
type: "post",
url: $("#btnSubscription").data("url"),
data: { fullName: $("#txtFullName").val(), emailAddress: $("#txtEmail").val() },
success: function () {
alert("email sent")
},
error: function () {
alert("An error occurred..")
}
});
}
Once you set up your .validate() all you need to do is call the .valid() method in your .click() handler. This is what submit does automatically, but you can call it manually with the .valid() method.
you should use type submit, and then you can use the submitHandler in order to manage other things you want to do, like this:
$("#formSubscription").validate({
submitHandler: function(form) {
// do other things for a valid form
form.submit();
}
});
Take a loot at the documentation: https://jqueryvalidation.org/validate/
put an if in the SendSubscription function:
if (yourValidationDidntPass) {
//do whatever you want
}
else {
$.ajax({...});
}

form is not refreshing after ajax submit and jquery validate

I have a form which I am submitting to my database, the form includes Jquery Validate plugin and ajax to submit.
The issue I am having is that after I click submit the form does not clear, it updates to database etc but I am just trying to clear the form and css highlight on the input field so someone could add a new record. Any help please?
CODE:
$(document).ready(function () {
$.validator.addMethod("time", function (value, element) {
return this.optional(element) || /^(([0-1]?[0-9])|([2][0-3])):([0-5]?[0-9])(:([0-5]?[0-9]))?$/i.test(value);
}, "Please enter a valid time.");
$("#newform").validate({
//validation
debug: false,
rules: {
Name: {
required: true,
minlength: 3,
},
Surname: {
required: true,
},
},
submitHandler: function (form) {
$.post('process.php', $("#newform").serialize(), function (data) {
$('#results').html(data);
$('#newform').reset();
});
}
});
});
HTML:
<form name="newform" id="newform" action="" method="POST">
<p>Name:</p>
<input type="text" id="pName" name="sName" /><br />
<p>Surname:</p>
<input type="date" id="pSName" name="pSName" /><br />
<input type="submit" name="submit" value="Submit">
</form>
<div id="results"><div>
You can use the following code to clear your form:
$('#newform').reset();
To focus on a specific <input> then you can use this after the reset() call:
$('input[name="sName"]').focus();
Try the following:
submitHandler: function (form) {
var jqxhr = $.post('process.php', $("#newform").serialize(), function (data) {
$('#results').html(data);
});
jqxhr.done(function() {
$('#newform')[0].reset();
});
}
$('#newform').reset();
The above code will do. But reading your comments I see that you will have to make the ajax call synchronous. Because if its asynchronous, you will clear the form before the submit request is actually processed on server side. That's the reason you see a clear form before process.php
In the ajax call pass async also in the object parameter-
{url:'xyz.com',async:false}

Categories