更改无效的输入背景颜色 [英] Changing Input background colour on invalid

查看:41
本文介绍了更改无效的输入背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有这个代码 https://codepen.io/jammydodger29/pen/RwgaVom 用户在字段中输入他们的详细信息的地方,根据其是否有效,输入的背景会发生变化.我目前的卡字段有问题.如果卡片无效,警报将触发,告诉用户卡片详细信息有误,但不会将颜色更改为粉红色,始终保持绿色(就好像它有效一样).另外,在提醒点击确定后,即使卡片字段仍然不正确,我仍然可以提交表单.代码如下:

<头><元字符集=utf-8"><元名称=视口"内容=宽度=设备宽度"><title>技术挑战</title><link href="style.css";rel=样式表"类型=文本/css";/><script src="script.js"></script><身体><div类=表单><表单ID =表单"form action="mailto:test@test.com";方法=POST"enctype=文本/纯文本"><div class="form-group"><label id="name-label";for=名称">名称:</label><输入类型=文本"名称=名称"id=名称"模式=[A-Za-z!#$%&'*+-/=?^_`{|}~]+";title=请输入一个有效的名称."类=表单控制"placeholder =输入你的名字"必需的/><br><div class="form-group"><label id="email-label";for=email">电子邮件:</label><输入类型=电子邮件"名称=电子邮件"id=电子邮件"类=表单控制"占位符=输入您的电子邮件"必需的/><br><div class="form-group"><label id="card-label";for=卡片">卡片:</label><输入id="cardInput"类型=文本"大小=24"最大长度=20"oninput=this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');";名称=cc_number"onblur="//保存输入字符串并去除非数字cc_number_saved = this.value;this.value = this.value.replace(/[^\d]/g, '');if(!checkLuhn(this.value)) {alert('对不起,这不是一个有效的数字 - 请再试一次!');}""onfocus="//恢复保存的字符串if(this.value != cc_number_saved) this.value = cc_number_saved;"placeholder=输入代理信用卡号码."必需的/><br><div class="form-group"><按钮类型=提交"id="提交"class =提交按钮">提交</表单>

</html>

input:required:valid, input:focus:valid {背景颜色:RGB(137,200,46);边框:RGB(60,60,59);}输入:不(:焦点):不(:占位符显示):无效{背景颜色:RGB(231,0,100);边框:RGB(60,60,59);}

函数checkLuhn(输入){总和 = 0;var numdigits = input.length;var 奇偶校验 = numdigits % 2;for(var i=0; i  9) digit -= 9;总和 += 数字;}返回(总和 % 10)== 0;}

对此的任何帮助将不胜感激.

解决方案

我不知道有效的数字输入是什么样的,所以我将把这部分的检查留给你.我将您的内联 js 提取到外部 js 文件中,因为如此大量的内联 js 阻碍了可读性.除此之外,您可以使用 formDOM.checkValidity() 来检查表单的所有字段是否都有效并且您还可以使用 field.setCustomValidity() 将字段设置为无效.

function checkLuhn(input){总和 = 0;var numdigits = input.length;var 奇偶校验 = numdigits % 2;for(var i=0; i  9) digit -= 9;总和 += 数字;}返回(总和 % 10)== 0;}让 cc_number_saved = "";函数 onBlurEvent(mythis) {cc_number_saved = mythis.value;mythis.value = mythis.value.replace(/[^\d]/g, '');if(!checkLuhn(mythis.value)) {alert('对不起,这不是一个有效的数字 - 请再试一次!');}mythis.setCustomValidity("无效字段");}功能 onFocusEvent(mythis) {//恢复保存的字符串//这个是来做什么的?if(mythis.value != cc_number_saved) mythis.value = cc_number_saved;}函数 onSubmitEvent(mythis) {如果 (!mythis.checkValidity()) {event.preventDefault();}}

input:required:valid, input:focus:valid {背景颜色:RGB(137,200,46);边框:RGB(60,60,59);}输入:不(:焦点):不(:占位符显示):无效{背景颜色:RGB(231,0,100);边框:RGB(60,60,59);}

<头><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>技术挑战</title><link href="style.css" rel="stylesheet" type="text/css"/><script src="script.js"></script><身体><div类=表单><form id = "form" form action="mailto:test@test.com" method="POST" enctype="text/plain"><div class="form-group"><label id="name-label" for="name">名称:</label><输入类型=文本"名称=名称"id="姓名"pattern="[A-Za-z!#$%&'*+-/=?^_`{|}~]+"title="请输入一个有效的名称."类=形式控制"placeholder="输入你的名字"必需的/><br><div class="form-group"><label id="email-label" for="email">电子邮件:</label><输入类型=电子邮件"名称=电子邮件"id="电子邮件"类=形式控制"placeholder="输入您的电子邮件"必需的/><br><div class="form-group"><label id="card-label" for="card">卡片:</label><输入id="卡片输入"类型=文本"大小=24"最大长度=20"oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');"名称="cc_number"onblur="onBlurEvent(this)"onfocus="onFocusEvent(this)"placeholder="输入代理信用卡号码."必需的/><br><div class="form-group"><button onsubmit"onSubmitEvent(this)" type="submit" id="submit" class="submit-button">提交</表单>

</html>

I currently have this code https://codepen.io/jammydodger29/pen/RwgaVom where the user inputs their details into the fields and depending if its valid or not the background of the input will change. I am currently having a problem with my card field. The alert will trigger if the card isn't valid telling the user that the card details is wrong but it won't change the colour to pink, constantly remaining green (as if its valid). In addition, after clicking ok on the alert, I can still submit the form even if the card field is still incorrect. The code for this is below:

<!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width">
        <title>Technical Challenge</title>
        <link href="style.css" rel="stylesheet" type="text/css" />
        <script src="script.js"></script>
      </head>
      <body>
        <div class = form>
          <form id = "form" form action="mailto:test@test.com" method="POST" enctype="text/plain">
            <div class="form-group">
              <label id="name-label" for="name">Name:</label>
              <input
                type="text"
                name="name"
                id="name"
                pattern="[A-Za-z!#$%&'*+-/=?^_`{|}~]+"
                title="Please enter a valid name."
                class="form-control"
                placeholder="Enter Your Name"
                required
              />
            
            <br>
            <div class="form-group">
              <label id="email-label" for="email">Email:</label>
              <input
                type="email"
                name="email"
                id="email"
                class="form-control"
                placeholder="Enter Your Email"
                required
            />
    
              <br>
            <div class="form-group">
              <label id="card-label" for="card">Card:</label>
              <input
                id="cardInput" 
                type="text" 
                size="24" 
                maxlength="20" 
                oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');"
                name="cc_number" 
                onblur="
                // save input string and strip out non-numbers
                cc_number_saved = this.value;
                this.value = this.value.replace(/[^\d]/g, '');
                if(!checkLuhn(this.value)) { 
                alert('Sorry, that is not a valid number - please try again!');
                }"
                " onfocus="
                // restore saved string
                if(this.value != cc_number_saved) this.value = cc_number_saved;
                "
                
                placeholder="Enter a Proxy Credit Card Number."
                required
              />
    
                <br>
            <div class="form-group">
              <button type="submit" id="submit" class="submit-button">
                Submit
              </button>
          </form>
         </div> 
      </body>
    </html>

input:required:valid, input:focus:valid {
  background-color: rgb(137,200,46);
  border: rgb(60,60,59);
}

input:not(:focus):not(:placeholder-shown):invalid {
  background-color: rgb(231,0,100);
  border: rgb(60,60,59);
}

function checkLuhn(input)
{
  var sum = 0;
  var numdigits = input.length;
  var parity = numdigits % 2;
  for(var i=0; i < numdigits; i++) {
    var digit = parseInt(input.charAt(i))
    if(i % 2 == parity) digit *= 2;
    if(digit > 9) digit -= 9;
    sum += digit;
  }
  return (sum % 10) == 0;
}

Any help with this would be really appreciated.

解决方案

I don't know what a valid number input looks like so I will leave checking of that part to you. I extracted your inline js to external js file because such a big amount of inline js hinders readability. Aside from that, you can use formDOM.checkValidity() to check if all the fields of a form are valid and you can also use field.setCustomValidity() to set a field to invalid.

function checkLuhn(input)
{
  var sum = 0;
  var numdigits = input.length;
  var parity = numdigits % 2;
  for(var i=0; i < numdigits; i++) {
    var digit = parseInt(input.charAt(i))
    if(i % 2 == parity) digit *= 2;
    if(digit > 9) digit -= 9;
    sum += digit;
  }
  return (sum % 10) == 0;
}
let cc_number_saved = "";
function onBlurEvent(mythis) {
  cc_number_saved = mythis.value;
  mythis.value = mythis.value.replace(/[^\d]/g, '');
  if(!checkLuhn(mythis.value)) { 
    alert('Sorry, that is not a valid number - please try again!');
  }
  mythis.setCustomValidity("Invalid field");
}
function onFocusEvent(mythis) {
  // restore saved string
  // What is this for?
  if(mythis.value != cc_number_saved) mythis.value = cc_number_saved;
}
function onSubmitEvent(mythis) {
  if (!mythis.checkValidity()) {
    event.preventDefault();
  }
}

input:required:valid, input:focus:valid {
  background-color: rgb(137,200,46);
  border: rgb(60,60,59);
}

input:not(:focus):not(:placeholder-shown):invalid {
  background-color: rgb(231,0,100);
  border: rgb(60,60,59);
}

<!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width">
        <title>Technical Challenge</title>
        <link href="style.css" rel="stylesheet" type="text/css" />
        <script src="script.js"></script>
      </head>
      <body>
        <div class = form>
          <form id = "form" form action="mailto:test@test.com" method="POST" enctype="text/plain">
            <div class="form-group">
              <label id="name-label" for="name">Name:</label>
              <input
                type="text"
                name="name"
                id="name"
                pattern="[A-Za-z!#$%&'*+-/=?^_`{|}~]+"
                title="Please enter a valid name."
                class="form-control"
                placeholder="Enter Your Name"
                required
              />
            
            <br>
            <div class="form-group">
              <label id="email-label" for="email">Email:</label>
              <input
                type="email"
                name="email"
                id="email"
                class="form-control"
                placeholder="Enter Your Email"
                required
            />
    
              <br>
            <div class="form-group">
              <label id="card-label" for="card">Card:</label>
              <input
                id="cardInput" 
                type="text" 
                size="24" 
                maxlength="20" 
                oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');"
                name="cc_number" 
                onblur="onBlurEvent(this)"
                onfocus="onFocusEvent(this)"
                placeholder="Enter a Proxy Credit Card Number."
                required
              />
    
                <br>
            <div class="form-group">
              <button onsubmit"onSubmitEvent(this)" type="submit" id="submit" class="submit-button">
                Submit
              </button>
          </form>
         </div> 
      </body>
    </html>

这篇关于更改无效的输入背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆