New to all this but essentially I'm trying to use HTML form validation via browser defaults. The form uses a JQuery script to submit the form. I've trawled through similar posts and updated my code but still no luck. If I click the Subscribe button with nothing entered, then there's no prompts presented.
HTML
<form class="form-inline" id="sub-form">
<div class="flex-fill mr-2">
<div class="mc-form-group-FNAME" style="display: inline">
<input type="name" class="form-control required" name="FNAME" id="mce-FNAME" value="" placeholder="First name" required />
</div>
<div class="mc-form-group-EMAIL" style="display: inline">
<input type="email" class="form-control required email" name="EMAIL" id="mce-EMAIL" value="" placeholder="Email address" required />
</div>
<button type="submit" class="btn btn-primary" id="subscribe-btn" onclick="submitForm()">Subscribe</button>
</div>
<div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_8a28f24e93a8a23b993145f05_2d6480ea6a" tabindex="-1" value=""></div>
</form>
JQuery/JS
//Mail Chimp form submission
$('#sub-form').MailChimpForm({
url: 'https://-.us19.list-manage.com/subscribe/post?u=8a28f24e93a8a23b993145f05&id=2d6480ea6a',
fields: '0:FNAME,1:EMAIL',
submitSelector: '#subscribe-btn',
customMessages: {
E001: 'This field can not be empty',
E003: 'Please enter a valid email address',
},
onFail: (message) => {
if ((message.indexOf("already") >= 0) || (message.indexOf("recent")) >=0) {
alert('This email address is already subscribed. Stay tuned for our newsletter!')
}
},
onOk: function() {
$('#subscribe-ok').modal('show');
$('#sub-form').each(function() {
this.reset();
});
}
});
UPDATE
So upon more testing the HTML validation works if I remove all the JQuery. As soon as I add it back in its gone. Any reason why my JS would break HTML validation?
Thanks everyone for the responses. In the end I opted for JQuery entirely and implemented ToolTipster and JQuery Validate. Final code below.
$("#sub-form").validate({
errorPlacement: function(error, element) {
var ele = $(element),
err = $(error),
msg = err.text();
if (msg != null && msg !== "") {
ele.tooltipster('content', msg);
ele.tooltipster('open'); //open only if the error message is not blank. By default jquery-validate will return a label with no actual text in it so we have to check the innerHTML.
console.log("form validation attempted")
}
},
unhighlight: function(element, errorClass, validClass) {
$(element).removeClass(errorClass).addClass(validClass).tooltipster('close');
},
rules: {
field1: {
required: true,
email: false
},
field2: {
required: true,
email: true
}
},
submitHandler: function(form) { // for demo
alert('valid form');
return false;
}
});
//Run validation on form for subscribe attempt
$('#subscribe-btn').click(function () {
if ($("#sub-form").valid()) {
console.log('hello - valid form');
} else {
console.log('uh oh invalid form');
}
});
Related
I work on a React project. I wrote HTML codes for create form. There is validation in HTML scripts. I wrote validations but validations doesn't work. The code is below. For example I want the relevant field to be red when the name is not entered or I want it to give a warning message when the name does not comply with the text rules. I must do it without any library. How can I fix it ?
import React, { Component } from 'react'
import EmployeeService from '../services/EmployeeService';
class CreateEmployeeComponent extends Component {
constructor(props) {
super(props)
this.state = {
id: this.props.match.params.id,
firstName: '',
lastName: '',
emailId: ''
}
}
componentDidMount(){
if(this.state.id === '_add'){
return
}else{
EmployeeService.getEmployeeById(this.state.id).then( (res) =>{
let employee = res.data;
this.setState({firstName: employee.firstName,
lastName: employee.lastName,
emailId : employee.emailId
});
});
}
}
saveOrUpdateEmployee = (e) => {
e.preventDefault();
let employee = {firstName: this.state.firstName, lastName: this.state.lastName, emailId: this.state.emailId};
console.log('employee => ' + JSON.stringify(employee));
// step 5
if(this.state.id === '_add'){
EmployeeService.createEmployee(employee).then(res =>{
this.props.history.push('/employees');
});
}else{
EmployeeService.updateEmployee(employee, this.state.id).then( res => {
this.props.history.push('/employees');
});
}
}
changeFirstNameHandler= (event) => {
this.setState({firstName: event.target.value});
}
changeLastNameHandler= (event) => {
this.setState({lastName: event.target.value});
}
changeEmailHandler= (event) => {
this.setState({emailId: event.target.value});
}
cancel(){
this.props.history.push('/employees');
}
getTitle(){
if(this.state.id === '_add'){
return <h3 className="text-center">Add Employee</h3>
}else{
return <h3 className="text-center">Update Employee</h3>
}
}
onSubmit = e => {
e.preventDefault();
}
render() {
return (
<div>
<br></br>
<div className = "container">
<div className = "row">
<div className = "card col-md-6 offset-md-3 offset-md-3">
{
this.getTitle()
}
<div className = "card-body">
<form onSubmit={this.onSubmit} noValidate>
<div className = "form-group">
<label for="validationCustom01" class="form-label">First name</label>
<input type='text' maxLength={20} pattern='[A-Za-z]' placeholder="First Name" name="firstName" className="form-control"
value={this.state.firstName} onChange={this.changeFirstNameHandler} required/>
</div>
<div className = "form-group">
<label> Last Name: </label>
<input type='text' maxLength={20} pattern='[A-Za-z]'class="form-control" placeholder="Last Name" name="lastName" className="form-control"
value={this.state.lastName} onChange={this.changeLastNameHandler} required/>
</div>
<div className = "form-group">
<label> Email Id: </label>
<input type='email' maxLength={35} pattern='[A-Za-z]' placeholder="Email Address" name="emailId" className="form-control"
value={this.state.emailId} onChange={this.changeEmailHandler} required/>
</div>
<button type="submit" className="btn btn-success" onClick={this.saveOrUpdateEmployee}>Save</button>
<button className="btn btn-danger" onClick={this.cancel.bind(this)} style={{marginLeft: "10px"}}>Cancel</button>
</form>
</div>
</div>
</div>
</div>
</div>
)
}
}
export default CreateEmployeeComponent
Remove noValidate from your <form> element.
Additionally, I've personally found that Formik and Yup can be a helpful library.
(Sorry I missed that "no libraries" wasa constraint)
Edit:
I was a muppet and forgot to change the pattern
You can do one of 2 things:
Remove maxLength and change the pattern to pattern="[A-Za-z]{1,20}"
Where 20 will be the new max-length (so 20 or 35, depending on the field)
Only change the pattern to be pattern="[A-Za-z]+"
The + is needed to ensure 1 or more of the [A-Za-z] regex is done. https://regexr.com/
Also don't forget to remove noValidate from your <form> element.
This answer may also prove helpful in setting custom validity status messages and callbacks.
I'm a bit of a novice with the implementation of multiple functions. However, I have a form where people can enter information which when submitted is posted to where I am collating the information. My code at the moment is:
component.html
<form name="hello"(ngSubmit)="onSubmit(helloForm); helloForm.reset();closeModal('custom-modal-2');openModal('custom-modal-3')" #helloForm="ngForm">
<input type="text" class = "box" placeholder="Name" name="name" ngModel required #name="ngModel"><br>
<input type="text" class = "box" placeholder="Email" email name="email" ngModel required #email="ngModel">
<re-captcha (resolved)="resolved($event)" siteKey="key"></re-captcha>
<br><input class="submit" type="submit" value="Submit">
</form>
component.ts
export class HelloDetailsComponent {public pageTitle = 'Contact Me';
constructor(private modalService: ModalService, private http: HttpClient) {}
resolved(captchaResponse: string) {
console.log(`Resolved captcha with response: ${captchaResponse}`);
}
openModal(id: string) {
this.modalService.open(id);
}
closeModal(id: string) {
this.modalService.close(id);
}
onSubmit(helloForm: NgForm) {
if (helloForm.valid) {
const email = helloForm.value;
const headers = new HttpHeaders({ 'Content-Type': 'application/json' });
this.http.post('formsent',
{Name: email.name, Email: email.email},
{ 'headers': headers }).hello(
response => {
console.log(response);
}
);
}
}
At the moment, when I press the submit button without filling out the form, the openModal('custom-modal-3') appears.
I would like to change this so that it only appears when the form is submitted and implement a separate modal for when the form is incomplete. Does anyone have any ideas?
A am making this forum type app and to create a post you go through a form with a textarea; I want to support Markdown. So to do that you kind of need to support new line functionality. When I press the enter key this error occurs:
This is the code
export default class CreatePost extends Component {
state = {
redirect: false,
Title: '',
Author: '',
Body: '',
};
updateState = e => {
this.setState({ [e.target.name]: e.target.value });
};
createPost = e => {
e.preventDefault();
if (this.state.Body !== '') {
this.props.createPost(this.state);
}
this.setState({ Title: '', Author: '', Body: '', redirect: true });
};
onEnterPress = e => {
if (e.keyCode === 13) {
e.preventDefault();
}
};
render() {
if (this.state.redirect) {
return <Redirect push to='/' />;
}
return (
<div className='createPost'>
<h1>Create Your Post!</h1>
<form onSubmit={this.createPost}>
<label className='input'>
Title:{' '}
<input
type='text'
name='Title'
value={this.state.Title}
onChange={this.updateState}
required
/>
</label>
<label className='input'>
Author:{' '}
<input
type='text'
name='Author'
value={this.state.Author}
onChange={this.updateState}
required
/>
</label>
<textarea
name='Body'
className='body'
value={this.state.Body}
onKeyDown={this.onEnterPress}
onChange={this.updateState}
></textarea>
<input type='submit' value='Submit' className='submitBTN' />
</form>
<Link className='home' to='/'>
Go Home
</Link>
</div>
);
}
}
I have tried the regular on press down function but It doesn't work.
Update #1
I got it to work but I still get the error.
You need to move the onEnterPress to the form itself, because the form also listens to the key presses.
<form onSubmit={this.createPost} onKeyDown={onEnterPress}>
Here is a fiddle.
I´m currently working on a login-page for a school-prohect. I´m using vue.js and tried to use axios to run my get-request. My problem is, that I don´t even get into .then() --> alert(TEST1) is the last thing showed.
I don´t get any error
Does anyone know why I have this problem and how to solve it?
Thanks!
CODE:
<template>
....
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6" id="formsCSS">
<form id="login" method="get">
<div class="form-group">
<input type="text" name="username" id="username" class="form-control" placeholder="Username" required maxlength="50">
</div>
<div class="form-group">
<input type="password" name="password" class="form-control" id="password" placeholder="Password" required>
</div>
<button #click="login" type="submit" name="login_button" class="block">Login</button>
</form>
....
</div>
</template>
<script>
//import axios from './node_modules/axios/index.js';
import axios from 'axios';
export default {
methods: {
login() {
var usrn = document.getElementById("username").value;
var passwd = document.getElementById("password").value;
var usesGranted = 50;
alert("TEST0");
this.doGetRequest(usrn, passwd, usesGranted, false);
},
doGetRequest(passwd, usrn, usesGranted, logedIn) {
alert("TEST1");
axios.get('https://moray.xyz/trawaapi/token/obtainToken.php', {
data: {
auth: {
username: usrn,
password: passwd
},
uses: usesGranted
}
})
.then((response) => {
//Informationen die für Requests benötigt werden in der sessionStorage abspeichern
alert("TEST2");
console.log(response);
sessionStorage.setItem("token", response);
sessionStorage.setItem("password", passwd);
sessionStorage.setItem("username", usrn);
sessionStorage.setItem("uses", usesGranted)
})
.catch((error) => {
//Neuen Token anfordern
if (error == 401) {
if (logedIn == true)
alert("....");
}
console.error(error);
});
}
}
};
</script>
You have to prevent form from being sent. Change remove onclick from button and add another event to the form tag:
<form #submit.prevent="yourFunction" id="login">
As we prevent Email sending and just running yourFunction - we do not need to use method attribute.
I am writing a login page with register and login options using AngularJS. There are three input fields: username, password and name. I want name field to appear when I click to register button and disappear when I click to login button. Therefore I want to change input field's class to 'hidden' on click and let css handle the job. How can I do it using AngularJS? Is there a better way to hide the name input field?
HTML:
<h2>Welcome to Mail Service</h2>
<form action="/action_page.php">
<div class="imgcontainer">
<img src="images/img_avatar2.png" alt="Avatar" class="avatar">
</div>
<div class="container">
<label><b>Username</b></label><br>
<input type="text" placeholder="Enter Username" name="uname" required ng-model="user.username"><br>
<label><b>Password</b></label><br>
<input type="password" placeholder="Enter Password" name="psw" required ng-model="user.password"><br>
<!-- NAME INPUT FIELD -->
<div class="textField-hidden">
<label><b>Name</b></label><br>
<input type="text" placeholder="Enter Name" ng-model="user.name">
</div><br>
<button type="submit" ng-click="login()">Login</button><br>
<button type="submit" ng-click="register()">Register</button>
</div>
</form>
AngularJS Controller:
app.controller('LoginCtrl', ['$scope', '$resource', '$location',
function($scope, $resource, $location)
{
$scope.login = function()
{
var loginRequest = $resource('/api/login');
loginRequest.save($scope.user, function(response)
{
});
};
$scope.register = function()
{
var registerRequest = $resource('/api/register');
loginRequest.save($scope.user, function(response)
{
});
};
}]);
You need to use ng-hide or ng-show directive (based on your context), and provide it with appropriate condition value like this:
$scope.showName = false;
$scope.login = function() {
// Your code
$scope.showName = false;
}
$scope.register = function() {
// Your code
$scope.showName = false;
}
Change your HTML accordingly:
<input ng-show="showName" type="{{type}}" placeholder="Enter Name" ng-model="user.name">
In this way, the input box will be shown only if the expression of ng-show evaluates to true. Alternatively, ng-if can be used similar to ng-show, but it works a bit different.
just populate a variable as true when you click register and set that variable as false when you click login.
<h2>Welcome to Mail Service</h2>
<form action="/action_page.php">
<div class="imgcontainer">
<img src="images/img_avatar2.png" alt="Avatar" class="avatar">
</div>
<div class="container">
<label><b>Username</b></label><br>
<input type="text" placeholder="Enter Username" name="uname" required ng-model="user.username"><br>
<label><b>Password</b></label><br>
<input type="password" placeholder="Enter Password" name="psw" required ng-model="user.password"><br>
<!-- NAME INPUT FIELD -->
<div class="textField-hidden" ng-show="register">
<label><b>Name</b></label><br>
<input type="text" placeholder="Enter Name" ng-model="user.name">
</div><br>
<button type="submit" ng-click="login()">Login</button><br>
<button type="submit" ng-click="register()">Register</button>
now populate $scope.register as true when you click register
app.controller('LoginCtrl', ['$scope', '$resource', '$location',
function($scope, $resource, $location)
{
$scope.register=false;
$scope.login = function()
{
var loginRequest = $resource('/api/login');
$scope.register=false;
loginRequest.save($scope.user, function(response)
{
});
};
$scope.register = function()
{
var registerRequest = $resource('/api/register');
$scope.register=true;
loginRequest.save($scope.user, function(response)
{
});
};
}]);
You can use a variable for input fields type and hide it
HTML:
<input type="{{type}}" placeholder="Enter Name" ng-model="user.name">
JS:
app.controller('LoginCtrl', ['$scope', '$resource', '$location',
function($scope, $resource, $location)
{
$scope.login = function()
{
$scope.type="hidden";
var loginRequest = $resource('/api/login');
loginRequest.save($scope.user, function(response)
{
});
};
$scope.register = function()
{
$scope.type="text";
var registerRequest = $resource('/api/register');
loginRequest.save($scope.user, function(response)
{
});
};
}]);
An alternative will be to use ng-if or ng-hide/ng-show defined on a $scope variable and trigger a boolean value for this variable according to your needs.